From: Pierre Ossman Date: Tue, 10 Jan 2023 13:30:37 +0000 (+0100) Subject: Return std::string instead of dynamic allocations X-Git-Tag: v1.13.90~87^2~14 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=337dbc392253af92b0577da062a5abc1d032b1ef;p=tigervnc.git Return std::string instead of dynamic allocations We mostly use classical C strings, but the memory management around them can get confusing and error prone. Let's use std::string for the cases where we need to return a newly allocated string. --- diff --git a/common/network/TcpSocket.cxx b/common/network/TcpSocket.cxx index 74143a40..ec36b33d 100644 --- a/common/network/TcpSocket.cxx +++ b/common/network/TcpSocket.cxx @@ -341,8 +341,9 @@ Socket* TcpListener::createSocket(int fd) { return new TcpSocket(fd); } -void TcpListener::getMyAddresses(std::list* result) { +std::list TcpListener::getMyAddresses() { struct addrinfo *ai, *current, hints; + std::list result; initSockets(); @@ -356,9 +357,11 @@ void TcpListener::getMyAddresses(std::list* result) { // Windows doesn't like NULL for service, so specify something if ((getaddrinfo(NULL, "1", &hints, &ai)) != 0) - return; + return result; for (current= ai; current != NULL; current = current->ai_next) { + char addr[INET6_ADDRSTRLEN]; + switch (current->ai_family) { case AF_INET: if (!UseIPv4) @@ -372,15 +375,15 @@ void TcpListener::getMyAddresses(std::list* result) { continue; } - char *addr = new char[INET6_ADDRSTRLEN]; - getnameinfo(current->ai_addr, current->ai_addrlen, addr, INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST); - result->push_back(addr); + result.push_back(addr); } freeaddrinfo(ai); + + return result; } int TcpListener::getMyPort() { @@ -707,7 +710,7 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { return pattern; } -char* TcpFilter::patternToStr(const TcpFilter::Pattern& p) { +std::string TcpFilter::patternToStr(const TcpFilter::Pattern& p) { char addr[INET6_ADDRSTRLEN + 2]; if (p.address.u.sa.sa_family == AF_INET) { @@ -739,5 +742,9 @@ char* TcpFilter::patternToStr(const TcpFilter::Pattern& p) { else snprintf(result, resultlen, "%c%s/%u", action, addr, p.prefixlen); - return result; + std::string out = result; + + delete [] result; + + return out; } diff --git a/common/network/TcpSocket.h b/common/network/TcpSocket.h index d008f194..c62dd78b 100644 --- a/common/network/TcpSocket.h +++ b/common/network/TcpSocket.h @@ -39,6 +39,7 @@ #endif #include +#include /* Tunnelling support. */ #define TUNNEL_PORT_OFFSET 5500 @@ -69,7 +70,7 @@ namespace network { virtual int getMyPort(); - static void getMyAddresses(std::list* result); + static std::list getMyAddresses(); protected: virtual Socket* createSocket(int fd); @@ -107,7 +108,7 @@ namespace network { vnc_sockaddr_t mask; // computed from address and prefix }; static Pattern parsePattern(const char* s); - static char* patternToStr(const Pattern& p); + static std::string patternToStr(const Pattern& p); protected: std::list filter; }; diff --git a/common/rfb/CConnection.cxx b/common/rfb/CConnection.cxx index 862c2c95..da036821 100644 --- a/common/rfb/CConnection.cxx +++ b/common/rfb/CConnection.cxx @@ -548,7 +548,7 @@ void CConnection::serverCutText(const char* str) strFree(serverClipboard); serverClipboard = NULL; - serverClipboard = latin1ToUTF8(str); + serverClipboard = strDup(latin1ToUTF8(str).c_str()); handleClipboardAnnounce(true); } @@ -612,7 +612,8 @@ void CConnection::handleClipboardProvide(uint32_t flags, strFree(serverClipboard); serverClipboard = NULL; - serverClipboard = convertLF((const char*)data[0], lengths[0]); + std::string filtered(convertLF((const char*)data[0], lengths[0])); + serverClipboard = strDup(filtered.c_str()); // FIXME: Should probably verify that this data was actually requested handleClipboardData(serverClipboard); @@ -681,9 +682,9 @@ void CConnection::announceClipboard(bool available) void CConnection::sendClipboardData(const char* data) { if (server.clipboardFlags() & rfb::clipboardProvide) { - CharArray filtered(convertCRLF(data)); - size_t sizes[1] = { strlen(filtered.buf) + 1 }; - const uint8_t* data[1] = { (const uint8_t*)filtered.buf }; + std::string filtered(convertCRLF(data)); + size_t sizes[1] = { filtered.size() + 1 }; + const uint8_t* data[1] = { (const uint8_t*)filtered.c_str() }; if (unsolicitedClipboardAttempt) { unsolicitedClipboardAttempt = false; @@ -697,9 +698,9 @@ void CConnection::sendClipboardData(const char* data) writer()->writeClipboardProvide(rfb::clipboardUTF8, sizes, data); } else { - CharArray latin1(utf8ToLatin1(data)); + std::string latin1(utf8ToLatin1(data)); - writer()->writeClientCutText(latin1.buf); + writer()->writeClientCutText(latin1.c_str()); } } diff --git a/common/rfb/CMsgHandler.cxx b/common/rfb/CMsgHandler.cxx index 2f91d5a5..f547f0a9 100644 --- a/common/rfb/CMsgHandler.cxx +++ b/common/rfb/CMsgHandler.cxx @@ -139,11 +139,8 @@ void CMsgHandler::handleClipboardCaps(uint32_t flags, const uint32_t* lengths) if (lengths[i] == 0) vlog.debug(" %s (only notify)", type); else { - char bytes[1024]; - - iecPrefix(lengths[i], "B", bytes, sizeof(bytes)); vlog.debug(" %s (automatically send up to %s)", - type, bytes); + type, iecPrefix(lengths[i], "B").c_str()); } } } diff --git a/common/rfb/CMsgReader.cxx b/common/rfb/CMsgReader.cxx index ba0380fc..42647119 100644 --- a/common/rfb/CMsgReader.cxx +++ b/common/rfb/CMsgReader.cxx @@ -277,8 +277,8 @@ bool CMsgReader::readServerCutText() } CharArray ca(len); is->readBytes(ca.buf, len); - CharArray filtered(convertLF(ca.buf, len)); - handler->serverCutText(filtered.buf); + std::string filtered(convertLF(ca.buf, len)); + handler->serverCutText(filtered.c_str()); return true; } diff --git a/common/rfb/CSecurityDH.cxx b/common/rfb/CSecurityDH.cxx index aab25671..9e67885c 100644 --- a/common/rfb/CSecurityDH.cxx +++ b/common/rfb/CSecurityDH.cxx @@ -104,11 +104,12 @@ bool CSecurityDH::readKey() void CSecurityDH::writeCredentials() { - CharArray username; - CharArray password; + std::string username; + std::string password; rdr::RandomStream rs; - (CSecurity::upg)->getUserPasswd(isSecure(), &username.buf, &password.buf); + (CSecurity::upg)->getUserPasswd(isSecure(), &username, &password); + std::vector bBytes(keyLength); if (!rs.hasData(keyLength)) throw ConnFailedException("failed to generate DH private key"); @@ -133,14 +134,12 @@ void CSecurityDH::writeCredentials() if (!rs.hasData(128)) throw ConnFailedException("failed to generate random padding"); rs.readBytes(buf, 128); - size_t len = strlen(username.buf); - if (len >= 64) + if (username.size() >= 64) throw AuthFailureException("username is too long"); - memcpy(buf, username.buf, len + 1); - len = strlen(password.buf); - if (len >= 64) + memcpy(buf, username.c_str(), username.size() + 1); + if (password.size() >= 64) throw AuthFailureException("password is too long"); - memcpy(buf + 64, password.buf, len + 1); + memcpy(buf + 64, password.c_str(), password.size() + 1); aes128_encrypt(&aesCtx, 128, (uint8_t *)buf, (uint8_t *)buf); rdr::OutStream* os = cc->getOutStream(); diff --git a/common/rfb/CSecurityMSLogonII.cxx b/common/rfb/CSecurityMSLogonII.cxx index 45c43c3f..d7e23715 100644 --- a/common/rfb/CSecurityMSLogonII.cxx +++ b/common/rfb/CSecurityMSLogonII.cxx @@ -93,11 +93,12 @@ bool CSecurityMSLogonII::readKey() void CSecurityMSLogonII::writeCredentials() { - CharArray username; - CharArray password; + std::string username; + std::string password; rdr::RandomStream rs; - (CSecurity::upg)->getUserPasswd(isSecure(), &username.buf, &password.buf); + (CSecurity::upg)->getUserPasswd(isSecure(), &username, &password); + std::vector bBytes(8); if (!rs.hasData(8)) throw ConnFailedException("failed to generate DH private key"); @@ -125,14 +126,12 @@ void CSecurityMSLogonII::writeCredentials() throw ConnFailedException("failed to generate random padding"); rs.readBytes(user, 256); rs.readBytes(pass, 64); - size_t len = strlen(username.buf); - if (len >= 256) + if (username.size() >= 256) throw AuthFailureException("username is too long"); - memcpy(user, username.buf, len + 1); - len = strlen(password.buf); - if (len >= 64) + memcpy(user, username.c_str(), username.size() + 1); + if (password.size() >= 64) throw AuthFailureException("password is too long"); - memcpy(pass, password.buf, len + 1); + memcpy(pass, password.c_str(), password.size() + 1); // DES-CBC with the original key as IV, and the reversed one as the DES key struct CBC_CTX(struct des_ctx, DES_BLOCK_SIZE) ctx; diff --git a/common/rfb/CSecurityPlain.cxx b/common/rfb/CSecurityPlain.cxx index 464dfcb5..7b75ef86 100644 --- a/common/rfb/CSecurityPlain.cxx +++ b/common/rfb/CSecurityPlain.cxx @@ -24,7 +24,6 @@ #include #include #include -#include #include @@ -34,16 +33,16 @@ bool CSecurityPlain::processMsg() { rdr::OutStream* os = cc->getOutStream(); - CharArray username; - CharArray password; + std::string username; + std::string password; - (CSecurity::upg)->getUserPasswd(cc->isSecure(), &username.buf, &password.buf); + (CSecurity::upg)->getUserPasswd(cc->isSecure(), &username, &password); // Return the response to the server - os->writeU32(strlen(username.buf)); - os->writeU32(strlen(password.buf)); - os->writeBytes(username.buf,strlen(username.buf)); - os->writeBytes(password.buf,strlen(password.buf)); + os->writeU32(username.size()); + os->writeU32(password.size()); + os->writeBytes(username.data(), username.size()); + os->writeBytes(password.data(), password.size()); os->flush(); return true; } diff --git a/common/rfb/CSecurityRSAAES.cxx b/common/rfb/CSecurityRSAAES.cxx index b1c273a4..f48e2523 100644 --- a/common/rfb/CSecurityRSAAES.cxx +++ b/common/rfb/CSecurityRSAAES.cxx @@ -433,29 +433,26 @@ bool CSecurityRSAAES::readSubtype() void CSecurityRSAAES::writeCredentials() { - CharArray username; - CharArray password; + std::string username; + std::string password; - (CSecurity::upg)->getUserPasswd( - isSecure(), - subtype == secTypeRA2UserPass ? &username.buf : NULL, &password.buf - ); - size_t len; - if (username.buf) { - len = strlen(username.buf); - if (len > 255) + if (subtype == secTypeRA2UserPass) + (CSecurity::upg)->getUserPasswd(isSecure(), &username, &password); + else + (CSecurity::upg)->getUserPasswd(isSecure(), NULL, &password); + + if (subtype == secTypeRA2UserPass) { + if (username.size() > 255) throw AuthFailureException("username is too long"); - raos->writeU8(len); - if (len) - raos->writeBytes(username.buf, len); + raos->writeU8(username.size()); + raos->writeBytes(username.data(), username.size()); } else { raos->writeU8(0); } - len = strlen(password.buf); - if (len > 255) + + if (password.size() > 255) throw AuthFailureException("password is too long"); - raos->writeU8(len); - if (len) - raos->writeBytes(password.buf, len); + raos->writeU8(password.size()); + raos->writeBytes(password.data(), password.size()); raos->flush(); } diff --git a/common/rfb/CSecurityVncAuth.cxx b/common/rfb/CSecurityVncAuth.cxx index 41eb5484..875e088a 100644 --- a/common/rfb/CSecurityVncAuth.cxx +++ b/common/rfb/CSecurityVncAuth.cxx @@ -29,7 +29,6 @@ #include #include -#include #include #include #include @@ -55,14 +54,13 @@ bool CSecurityVncAuth::processMsg() // Read the challenge & obtain the user's password uint8_t challenge[vncAuthChallengeSize]; is->readBytes(challenge, vncAuthChallengeSize); - PlainPasswd passwd; - (CSecurity::upg)->getUserPasswd(cc->isSecure(), 0, &passwd.buf); + std::string passwd; + (CSecurity::upg)->getUserPasswd(cc->isSecure(), 0, &passwd); // Calculate the correct response uint8_t key[8]; - int pwdLen = strlen(passwd.buf); - for (int i=0; i<8; i++) - key[i] = igetDefaultStr(); + std::string def_str = current->getDefaultStr(); const char* desc = current->getDescription(); fprintf(stderr," %-*s -", nameWidth, current->getName()); int column = strlen(current->getName()); @@ -157,11 +157,10 @@ void Configuration::list(int width, int nameWidth) { if (!s) break; } - if (def_str) { - if (column + (int)strlen(def_str) + 11 > width) + if (!def_str.empty()) { + if (column + (int)def_str.size() + 11 > width) fprintf(stderr,"\n%*s",nameWidth+4,""); - fprintf(stderr," (default=%s)\n",def_str); - strFree(def_str); + fprintf(stderr," (default=%s)\n",def_str.c_str()); } else { fprintf(stderr,"\n"); } @@ -257,12 +256,11 @@ bool AliasParameter::setParam() { return param->setParam(); } -char* -AliasParameter::getDefaultStr() const { - return 0; +std::string AliasParameter::getDefaultStr() const { + return ""; } -char* AliasParameter::getValueStr() const { +std::string AliasParameter::getValueStr() const { return param->getValueStr(); } @@ -313,13 +311,12 @@ void BoolParameter::setParam(bool b) { vlog.debug("set %s(Bool) to %d", getName(), value); } -char* -BoolParameter::getDefaultStr() const { - return strDup(def_value ? "1" : "0"); +std::string BoolParameter::getDefaultStr() const { + return def_value ? "1" : "0"; } -char* BoolParameter::getValueStr() const { - return strDup(value ? "1" : "0"); +std::string BoolParameter::getValueStr() const { + return value ? "1" : "0"; } bool BoolParameter::isBool() const { @@ -355,15 +352,14 @@ IntParameter::setParam(int v) { return true; } -char* -IntParameter::getDefaultStr() const { - char* result = new char[16]; +std::string IntParameter::getDefaultStr() const { + char result[16]; sprintf(result, "%d", def_value); return result; } -char* IntParameter::getValueStr() const { - char* result = new char[16]; +std::string IntParameter::getValueStr() const { + char result[16]; sprintf(result, "%d", value); return result; } @@ -400,13 +396,13 @@ bool StringParameter::setParam(const char* v) { return value != 0; } -char* StringParameter::getDefaultStr() const { - return strDup(def_value); +std::string StringParameter::getDefaultStr() const { + return def_value; } -char* StringParameter::getValueStr() const { +std::string StringParameter::getValueStr() const { LOCK_CONFIG; - return strDup(value); + return std::string(value); } StringParameter::operator const char *() const { @@ -457,11 +453,11 @@ void BinaryParameter::setParam(const uint8_t* v, size_t len) { } } -char* BinaryParameter::getDefaultStr() const { +std::string BinaryParameter::getDefaultStr() const { return binToHex(def_value, def_length); } -char* BinaryParameter::getValueStr() const { +std::string BinaryParameter::getValueStr() const { LOCK_CONFIG; return binToHex(value, length); } diff --git a/common/rfb/Configuration.h b/common/rfb/Configuration.h index 318b6b8d..20552364 100644 --- a/common/rfb/Configuration.h +++ b/common/rfb/Configuration.h @@ -171,8 +171,8 @@ namespace rfb { virtual bool setParam(const char* value) = 0; virtual bool setParam(); - virtual char* getDefaultStr() const = 0; - virtual char* getValueStr() const = 0; + virtual std::string getDefaultStr() const = 0; + virtual std::string getValueStr() const = 0; virtual bool isBool() const; virtual void setImmutable(); @@ -195,8 +195,8 @@ namespace rfb { ConfigurationObject co=ConfGlobal); virtual bool setParam(const char* value); virtual bool setParam(); - virtual char* getDefaultStr() const; - virtual char* getValueStr() const; + virtual std::string getDefaultStr() const; + virtual std::string getValueStr() const; virtual bool isBool() const; virtual void setImmutable(); private: @@ -210,8 +210,8 @@ namespace rfb { virtual bool setParam(const char* value); virtual bool setParam(); virtual void setParam(bool b); - virtual char* getDefaultStr() const; - virtual char* getValueStr() const; + virtual std::string getDefaultStr() const; + virtual std::string getValueStr() const; virtual bool isBool() const; operator bool() const; protected: @@ -227,8 +227,8 @@ namespace rfb { using VoidParameter::setParam; virtual bool setParam(const char* value); virtual bool setParam(int v); - virtual char* getDefaultStr() const; - virtual char* getValueStr() const; + virtual std::string getDefaultStr() const; + virtual std::string getValueStr() const; operator int() const; protected: int value; @@ -244,13 +244,9 @@ namespace rfb { ConfigurationObject co=ConfGlobal); virtual ~StringParameter(); virtual bool setParam(const char* value); - virtual char* getDefaultStr() const; - virtual char* getValueStr() const; + virtual std::string getDefaultStr() const; + virtual std::string getValueStr() const; operator const char*() const; - - // getData() returns a copy of the data - it must be delete[]d by the - // caller. - char* getData() const { return getValueStr(); } protected: char* value; char* def_value; @@ -265,8 +261,8 @@ namespace rfb { virtual ~BinaryParameter(); virtual bool setParam(const char* value); virtual void setParam(const uint8_t* v, size_t l); - virtual char* getDefaultStr() const; - virtual char* getValueStr() const; + virtual std::string getDefaultStr() const; + virtual std::string getValueStr() const; std::vector getData() const; diff --git a/common/rfb/DecodeManager.cxx b/common/rfb/DecodeManager.cxx index b9faf689..b6dd81f4 100644 --- a/common/rfb/DecodeManager.cxx +++ b/common/rfb/DecodeManager.cxx @@ -211,8 +211,6 @@ void DecodeManager::logStats() double ratio; - char a[1024], b[1024]; - rects = 0; pixels = bytes = equivalent = 0; @@ -228,22 +226,21 @@ void DecodeManager::logStats() ratio = (double)stats[i].equivalent / stats[i].bytes; - siPrefix(stats[i].rects, "rects", a, sizeof(a)); - siPrefix(stats[i].pixels, "pixels", b, sizeof(b)); - vlog.info(" %s: %s, %s", encodingName(i), a, b); - iecPrefix(stats[i].bytes, "B", a, sizeof(a)); + vlog.info(" %s: %s, %s", encodingName(i), + siPrefix(stats[i].rects, "rects").c_str(), + siPrefix(stats[i].pixels, "pixels").c_str()); vlog.info(" %*s %s (1:%g ratio)", (int)strlen(encodingName(i)), "", - a, ratio); + iecPrefix(stats[i].bytes, "B").c_str(), ratio); } ratio = (double)equivalent / bytes; - siPrefix(rects, "rects", a, sizeof(a)); - siPrefix(pixels, "pixels", b, sizeof(b)); - vlog.info(" Total: %s, %s", a, b); - iecPrefix(bytes, "B", a, sizeof(a)); - vlog.info(" %s (1:%g ratio)", a, ratio); + vlog.info(" Total: %s, %s", + siPrefix(rects, "rects").c_str(), + siPrefix(pixels, "pixels").c_str()); + vlog.info(" %s (1:%g ratio)", + iecPrefix(bytes, "B").c_str(), ratio); } void DecodeManager::setThreadException(const rdr::Exception& e) diff --git a/common/rfb/EncodeManager.cxx b/common/rfb/EncodeManager.cxx index a955a2c1..e2571cab 100644 --- a/common/rfb/EncodeManager.cxx +++ b/common/rfb/EncodeManager.cxx @@ -177,8 +177,6 @@ void EncodeManager::logStats() double ratio; - char a[1024], b[1024]; - rects = 0; pixels = bytes = equivalent = 0; @@ -194,13 +192,12 @@ void EncodeManager::logStats() ratio = (double)copyStats.equivalent / copyStats.bytes; - siPrefix(copyStats.rects, "rects", a, sizeof(a)); - siPrefix(copyStats.pixels, "pixels", b, sizeof(b)); - vlog.info(" %s: %s, %s", "Copies", a, b); - iecPrefix(copyStats.bytes, "B", a, sizeof(a)); + vlog.info(" %s: %s, %s", "Copies", + siPrefix(copyStats.rects, "rects").c_str(), + siPrefix(copyStats.pixels, "pixels").c_str()); vlog.info(" %*s %s (1:%g ratio)", (int)strlen("Copies"), "", - a, ratio); + iecPrefix(copyStats.bytes, "B").c_str(), ratio); } for (i = 0;i < stats.size();i++) { @@ -225,23 +222,22 @@ void EncodeManager::logStats() ratio = (double)stats[i][j].equivalent / stats[i][j].bytes; - siPrefix(stats[i][j].rects, "rects", a, sizeof(a)); - siPrefix(stats[i][j].pixels, "pixels", b, sizeof(b)); - vlog.info(" %s: %s, %s", encoderTypeName((EncoderType)j), a, b); - iecPrefix(stats[i][j].bytes, "B", a, sizeof(a)); + vlog.info(" %s: %s, %s", encoderTypeName((EncoderType)j), + siPrefix(stats[i][j].rects, "rects").c_str(), + siPrefix(stats[i][j].pixels, "pixels").c_str()); vlog.info(" %*s %s (1:%g ratio)", (int)strlen(encoderTypeName((EncoderType)j)), "", - a, ratio); + iecPrefix(stats[i][j].bytes, "B").c_str(), ratio); } } ratio = (double)equivalent / bytes; - siPrefix(rects, "rects", a, sizeof(a)); - siPrefix(pixels, "pixels", b, sizeof(b)); - vlog.info(" Total: %s, %s", a, b); - iecPrefix(bytes, "B", a, sizeof(a)); - vlog.info(" %s (1:%g ratio)", a, ratio); + vlog.info(" Total: %s, %s", + siPrefix(rects, "rects").c_str(), + siPrefix(pixels, "pixels").c_str()); + vlog.info(" %s (1:%g ratio)", + iecPrefix(bytes, "B").c_str(), ratio); } bool EncodeManager::supported(int encoding) diff --git a/common/rfb/Hostname.h b/common/rfb/Hostname.h index 341f69e1..8e57f31d 100644 --- a/common/rfb/Hostname.h +++ b/common/rfb/Hostname.h @@ -38,7 +38,9 @@ namespace rfb { return true; } - static void getHostAndPort(const char* hi, char** host, int* port, int basePort=5900) { + static void getHostAndPort(const char* hi, std::string* host, + int* port, int basePort=5900) + { const char* hostStart; const char* hostEnd; const char* portStart; @@ -86,14 +88,9 @@ namespace rfb { hostEnd--; if (hostStart == hostEnd) - *host = strDup("localhost"); - else { - size_t len; - len = hostEnd - hostStart + 1; - *host = new char[len]; - strncpy(*host, hostStart, len-1); - (*host)[len-1] = '\0'; - } + *host = "localhost"; + else + *host = std::string(hostStart, hostEnd - hostStart); if (portStart == NULL) *port = basePort; diff --git a/common/rfb/LogWriter.cxx b/common/rfb/LogWriter.cxx index 6df82d8e..a86e9652 100644 --- a/common/rfb/LogWriter.cxx +++ b/common/rfb/LogWriter.cxx @@ -123,7 +123,7 @@ bool LogParameter::setParam(const char* v) { LogWriter::setLogParams("*::0"); StringParameter::setParam(v); CharArray logParam; - CharArray params(getData()); + CharArray params(strDup(getValueStr().c_str())); while (params.buf) { strSplit(params.buf, ',', &logParam.buf, ¶ms.buf); if (strlen(logParam.buf) && !LogWriter::setLogParams(logParam.buf)) diff --git a/common/rfb/SConnection.cxx b/common/rfb/SConnection.cxx index a30e9187..211fbd98 100644 --- a/common/rfb/SConnection.cxx +++ b/common/rfb/SConnection.cxx @@ -384,7 +384,7 @@ void SConnection::clientCutText(const char* str) strFree(clientClipboard); clientClipboard = NULL; - clientClipboard = latin1ToUTF8(str); + clientClipboard = strDup(latin1ToUTF8(str).c_str()); handleClipboardAnnounce(true); } @@ -433,7 +433,8 @@ void SConnection::handleClipboardProvide(uint32_t flags, strFree(clientClipboard); clientClipboard = NULL; - clientClipboard = convertLF((const char*)data[0], lengths[0]); + std::string filtered(convertLF((const char*)data[0], lengths[0])); + clientClipboard = strDup(filtered.c_str()); // FIXME: Should probably verify that this data was actually requested handleClipboardData(clientClipboard); @@ -594,9 +595,9 @@ void SConnection::sendClipboardData(const char* data) { if (client.supportsEncoding(pseudoEncodingExtendedClipboard) && (client.clipboardFlags() & rfb::clipboardProvide)) { - CharArray filtered(convertCRLF(data)); - size_t sizes[1] = { strlen(filtered.buf) + 1 }; - const uint8_t* data[1] = { (const uint8_t*)filtered.buf }; + std::string filtered(convertCRLF(data)); + size_t sizes[1] = { filtered.size() + 1 }; + const uint8_t* data[1] = { (const uint8_t*)filtered.c_str() }; if (unsolicitedClipboardAttempt) { unsolicitedClipboardAttempt = false; @@ -610,9 +611,9 @@ void SConnection::sendClipboardData(const char* data) writer()->writeClipboardProvide(rfb::clipboardUTF8, sizes, data); } else { - CharArray latin1(utf8ToLatin1(data)); + std::string latin1(utf8ToLatin1(data)); - writer()->writeServerCutText(latin1.buf); + writer()->writeServerCutText(latin1.c_str()); } } diff --git a/common/rfb/SMsgHandler.cxx b/common/rfb/SMsgHandler.cxx index 3eccd92d..092d9f7e 100644 --- a/common/rfb/SMsgHandler.cxx +++ b/common/rfb/SMsgHandler.cxx @@ -106,11 +106,8 @@ void SMsgHandler::handleClipboardCaps(uint32_t flags, const uint32_t* lengths) if (lengths[i] == 0) vlog.debug(" %s (only notify)", type); else { - char bytes[1024]; - - iecPrefix(lengths[i], "B", bytes, sizeof(bytes)); vlog.debug(" %s (automatically send up to %s)", - type, bytes); + type, iecPrefix(lengths[i], "B").c_str()); } } } diff --git a/common/rfb/SMsgReader.cxx b/common/rfb/SMsgReader.cxx index 5ff07e23..3fddf302 100644 --- a/common/rfb/SMsgReader.cxx +++ b/common/rfb/SMsgReader.cxx @@ -316,8 +316,8 @@ bool SMsgReader::readClientCutText() CharArray ca(len); is->readBytes(ca.buf, len); - CharArray filtered(convertLF(ca.buf, len)); - handler->clientCutText(filtered.buf); + std::string filtered(convertLF(ca.buf, len)); + handler->clientCutText(filtered.c_str()); return true; } diff --git a/common/rfb/SSecurityPlain.cxx b/common/rfb/SSecurityPlain.cxx index ab3a2391..018ca517 100644 --- a/common/rfb/SSecurityPlain.cxx +++ b/common/rfb/SSecurityPlain.cxx @@ -45,7 +45,8 @@ StringParameter PasswordValidator::plainUsers bool PasswordValidator::validUser(const char* username) { - CharArray users(plainUsers.getValueStr()), user; + CharArray users(strDup(plainUsers.getValueStr().c_str())); + CharArray user; while (users.buf) { strSplit(users.buf, ',', &user.buf, &users.buf); diff --git a/common/rfb/UserPasswdGetter.h b/common/rfb/UserPasswdGetter.h index 27775cc3..db7df396 100644 --- a/common/rfb/UserPasswdGetter.h +++ b/common/rfb/UserPasswdGetter.h @@ -17,16 +17,20 @@ */ #ifndef __RFB_USERPASSWDGETTER_H__ #define __RFB_USERPASSWDGETTER_H__ + +#include + namespace rfb { class UserPasswdGetter { public: // getUserPasswd gets the username and password. This might involve a // dialog, getpass(), etc. The user buffer pointer can be null, in which - // case no user name will be retrieved. The caller MUST delete [] the - // result(s). - virtual void getUserPasswd(bool secure, char** user, char** password)=0; + // case no user name will be retrieved. + virtual void getUserPasswd(bool secure, std::string* user, + std::string* password)=0; virtual ~UserPasswdGetter() {} }; } + #endif diff --git a/common/rfb/util.cxx b/common/rfb/util.cxx index d1ba9200..30cf0300 100644 --- a/common/rfb/util.cxx +++ b/common/rfb/util.cxx @@ -66,10 +66,6 @@ namespace rfb { delete [] s; } - void strFree(wchar_t* s) { - delete [] s; - } - bool strSplit(const char* src, const char limiter, char** out1, char** out2, bool fromEnd) { CharArray out1old, out2old; @@ -139,9 +135,12 @@ namespace rfb { } } - char* binToHex(const uint8_t* in, size_t inlen) { - char* out = new char[inlen*2+1](); - binToHex(in, inlen, out, inlen*2); + std::string binToHex(const uint8_t* in, size_t inlen) { + char* buffer = new char[inlen*2+1](); + std::string out; + binToHex(in, inlen, buffer, inlen*2); + out = buffer; + delete [] buffer; return out; } @@ -185,19 +184,16 @@ namespace rfb { return out; } - char* convertLF(const char* src, size_t bytes) + std::string convertLF(const char* src, size_t bytes) { - char* buffer; size_t sz; + std::string out; - char* out; const char* in; size_t in_len; - // Always include space for a NULL - sz = 1; - // Compute output size + sz = 0; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { @@ -215,44 +211,39 @@ namespace rfb { in_len--; } - // Alloc - buffer = new char[sz]; - memset(buffer, 0, sz); + // Reserve space + out.reserve(sz); // And convert - out = buffer; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { if (*in != '\r') { - *out++ = *in++; + out += *in++; in_len--; continue; } if ((in_len < 2) || (*(in+1) != '\n')) - *out++ = '\n'; + out += '\n'; in++; in_len--; } - return buffer; + return out; } - char* convertCRLF(const char* src, size_t bytes) + std::string convertCRLF(const char* src, size_t bytes) { - char* buffer; + std::string out; size_t sz; - char* out; const char* in; size_t in_len; - // Always include space for a NULL - sz = 1; - // Compute output size + sz = 0; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { @@ -270,35 +261,30 @@ namespace rfb { in_len--; } - // Alloc - buffer = new char[sz]; - memset(buffer, 0, sz); + // Reserve space + out.reserve(sz); // And convert - out = buffer; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { if (*in == '\n') { if ((in == src) || (*(in-1) != '\r')) - *out++ = '\r'; + out += '\r'; } - *out = *in; + out += *in; if (*in == '\r') { - if ((in_len < 2) || (*(in+1) != '\n')) { - out++; - *out = '\n'; - } + if ((in_len < 2) || (*(in+1) != '\n')) + out += '\n'; } - out++; in++; in_len--; } - return buffer; + return out; } size_t ucs4ToUTF8(unsigned src, char dst[5]) { @@ -438,18 +424,15 @@ namespace rfb { return 2; } - char* latin1ToUTF8(const char* src, size_t bytes) { - char* buffer; + std::string latin1ToUTF8(const char* src, size_t bytes) { + std::string out; size_t sz; - char* out; const char* in; size_t in_len; - // Always include space for a NULL - sz = 1; - // Compute output size + sz = 0; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { @@ -459,35 +442,32 @@ namespace rfb { in_len--; } - // Alloc - buffer = new char[sz]; - memset(buffer, 0, sz); + // Reserve space + out.reserve(sz); // And convert - out = buffer; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { - out += ucs4ToUTF8(*(const unsigned char*)in, out); + char buf[5]; + ucs4ToUTF8(*(const unsigned char*)in, buf); + out += buf; in++; in_len--; } - return buffer; + return out; } - char* utf8ToLatin1(const char* src, size_t bytes) { - char* buffer; + std::string utf8ToLatin1(const char* src, size_t bytes) { + std::string out; size_t sz; - char* out; const char* in; size_t in_len; - // Always include space for a NULL - sz = 1; - // Compute output size + sz = 0; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { @@ -500,12 +480,10 @@ namespace rfb { sz++; } - // Alloc - buffer = new char[sz]; - memset(buffer, 0, sz); + // Reserve space + out.reserve(sz); // And convert - out = buffer; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { @@ -517,27 +495,24 @@ namespace rfb { in_len -= len; if (ucs > 0xff) - *out++ = '?'; + out += '?'; else - *out++ = (unsigned char)ucs; + out += (unsigned char)ucs; } - return buffer; + return out; } - char* utf16ToUTF8(const wchar_t* src, size_t units) + std::string utf16ToUTF8(const wchar_t* src, size_t units) { - char* buffer; + std::string out; size_t sz; - char* out; const wchar_t* in; size_t in_len; - // Always include space for a NULL - sz = 1; - // Compute output size + sz = 0; in = src; in_len = units; while ((in_len > 0) && (*in != '\0')) { @@ -552,41 +527,38 @@ namespace rfb { sz += ucs4ToUTF8(ucs, buf); } - // Alloc - buffer = new char[sz]; - memset(buffer, 0, sz); + // Reserve space + out.reserve(sz); // And convert - out = buffer; in = src; in_len = units; while ((in_len > 0) && (*in != '\0')) { size_t len; unsigned ucs; + char buf[5]; len = utf16ToUCS4(in, in_len, &ucs); in += len; in_len -= len; - out += ucs4ToUTF8(ucs, out); + ucs4ToUTF8(ucs, buf); + out += buf; } - return buffer; + return out; } - wchar_t* utf8ToUTF16(const char* src, size_t bytes) + std::wstring utf8ToUTF16(const char* src, size_t bytes) { - wchar_t* buffer; + std::wstring out; size_t sz; - wchar_t* out; const char* in; size_t in_len; - // Always include space for a NULL - sz = 1; - // Compute output size + sz = 0; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { @@ -601,26 +573,26 @@ namespace rfb { sz += ucs4ToUTF16(ucs, buf); } - // Alloc - buffer = new wchar_t[sz]; - memset(buffer, 0, sz * sizeof(wchar_t)); + // Reserve space + out.reserve(sz); // And convert - out = buffer; in = src; in_len = bytes; while ((in_len > 0) && (*in != '\0')) { size_t len; unsigned ucs; + wchar_t buf[3]; len = utf8ToUCS4(in, in_len, &ucs); in += len; in_len -= len; - out += ucs4ToUTF16(ucs, out); + ucs4ToUTF16(ucs, buf); + out += buf; } - return buffer; + return out; } unsigned msBetween(const struct timeval *first, @@ -657,12 +629,12 @@ namespace rfb { return false; } - static size_t doPrefix(long long value, const char *unit, - char *buffer, size_t maxlen, - unsigned divisor, const char **prefixes, - size_t prefixCount, int precision) { + static std::string doPrefix(long long value, const char *unit, + unsigned divisor, const char **prefixes, + size_t prefixCount, int precision) { + char buffer[256]; double newValue; - size_t prefix, len; + size_t prefix; newValue = value; prefix = 0; @@ -673,11 +645,11 @@ namespace rfb { prefix++; } - len = snprintf(buffer, maxlen, "%.*g %s%s", precision, newValue, - (prefix == 0) ? "" : prefixes[prefix-1], unit); - buffer[maxlen-1] = '\0'; + snprintf(buffer, sizeof(buffer), "%.*g %s%s", precision, newValue, + (prefix == 0) ? "" : prefixes[prefix-1], unit); + buffer[sizeof(buffer)-1] = '\0'; - return len; + return buffer; } static const char *siPrefixes[] = @@ -685,16 +657,16 @@ namespace rfb { static const char *iecPrefixes[] = { "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi" }; - size_t siPrefix(long long value, const char *unit, - char *buffer, size_t maxlen, int precision) { - return doPrefix(value, unit, buffer, maxlen, 1000, siPrefixes, + std::string siPrefix(long long value, const char *unit, + int precision) { + return doPrefix(value, unit, 1000, siPrefixes, sizeof(siPrefixes)/sizeof(*siPrefixes), precision); } - size_t iecPrefix(long long value, const char *unit, - char *buffer, size_t maxlen, int precision) { - return doPrefix(value, unit, buffer, maxlen, 1024, iecPrefixes, + std::string iecPrefix(long long value, const char *unit, + int precision) { + return doPrefix(value, unit, 1024, iecPrefixes, sizeof(iecPrefixes)/sizeof(*iecPrefixes), precision); } diff --git a/common/rfb/util.h b/common/rfb/util.h index e7d716fe..d8d7c653 100644 --- a/common/rfb/util.h +++ b/common/rfb/util.h @@ -28,6 +28,7 @@ #include #include +#include #include struct timeval; @@ -59,7 +60,6 @@ namespace rfb { char* strDup(const char* s); void strFree(char* s); - void strFree(wchar_t* s); // Returns true if split successful. Returns false otherwise. // ALWAYS *copies* first part of string to out1 buffer. @@ -79,17 +79,16 @@ namespace rfb { // Conversion to and from a hex string void binToHex(const uint8_t* in, size_t inlen, char* out, size_t outlen); - char* binToHex(const uint8_t* in, size_t inlen); + std::string binToHex(const uint8_t* in, size_t inlen); bool hexToBin(const char* in, size_t inlen, uint8_t* out, size_t outlen); std::vector hexToBin(const char* in, size_t inlen); // Makes sure line endings are in a certain format - char* convertLF(const char* src, size_t bytes = (size_t)-1); - char* convertCRLF(const char* src, size_t bytes = (size_t)-1); + std::string convertLF(const char* src, size_t bytes = (size_t)-1); + std::string convertCRLF(const char* src, size_t bytes = (size_t)-1); - // Convertions between various Unicode formats. The returned strings are - // always null terminated and must be freed using strFree(). + // Convertions between various Unicode formats size_t ucs4ToUTF8(unsigned src, char dst[5]); size_t utf8ToUCS4(const char* src, size_t max, unsigned* dst); @@ -97,11 +96,11 @@ namespace rfb { size_t ucs4ToUTF16(unsigned src, wchar_t dst[3]); size_t utf16ToUCS4(const wchar_t* src, size_t max, unsigned* dst); - char* latin1ToUTF8(const char* src, size_t bytes = (size_t)-1); - char* utf8ToLatin1(const char* src, size_t bytes = (size_t)-1); + std::string latin1ToUTF8(const char* src, size_t bytes = (size_t)-1); + std::string utf8ToLatin1(const char* src, size_t bytes = (size_t)-1); - char* utf16ToUTF8(const wchar_t* src, size_t units = (size_t)-1); - wchar_t* utf8ToUTF16(const char* src, size_t bytes = (size_t)-1); + std::string utf16ToUTF8(const wchar_t* src, size_t units = (size_t)-1); + std::wstring utf8ToUTF16(const char* src, size_t bytes = (size_t)-1); // HELPER functions for timeout handling @@ -129,10 +128,10 @@ namespace rfb { bool isBefore(const struct timeval *first, const struct timeval *second); - size_t siPrefix(long long value, const char *unit, - char *buffer, size_t maxlen, int precision=6); - size_t iecPrefix(long long value, const char *unit, - char *buffer, size_t maxlen, int precision=6); + std::string siPrefix(long long value, const char *unit, + int precision=6); + std::string iecPrefix(long long value, const char *unit, + int precision=6); } // Some platforms (e.g. Windows) include max() and min() macros in their diff --git a/tests/perf/fbperf.cxx b/tests/perf/fbperf.cxx index 5d626602..dddf19fb 100644 --- a/tests/perf/fbperf.cxx +++ b/tests/perf/fbperf.cxx @@ -322,7 +322,6 @@ static void dotest(TestWindow* win) double time[3]; double delay, rate; - char s[1024]; // Run the test several times at different resolutions... dosubtest(win, 800, 600, &pixels[0], &frames[0], &time[0]); @@ -369,11 +368,9 @@ static void dotest(TestWindow* win) } fprintf(stderr, "Rendering delay: %g ms/frame\n", delay * 1000.0); - if (rate == 0.0) - strcpy(s, "N/A pixels/s"); - else - rfb::siPrefix(1.0 / rate, "pixels/s", s, sizeof(s)); - fprintf(stderr, "Rendering rate: %s\n", s); + fprintf(stderr, "Rendering rate: %s\n", + (rate == 0.0) ? "N/A pixels/s" : + rfb::siPrefix(1.0 / rate, "pixels/s").c_str()); fprintf(stderr, "Maximum FPS: %g fps @ 1920x1080\n", 1.0 / (delay + rate * 1920 * 1080)); } diff --git a/tests/unit/convertlf.cxx b/tests/unit/convertlf.cxx index 4dff9098..1645532a 100644 --- a/tests/unit/convertlf.cxx +++ b/tests/unit/convertlf.cxx @@ -50,38 +50,34 @@ static const char* escape(const char* input) static void testLF(const char* input, const char* expected) { - char* output; + std::string output; printf("convertLF(\"%s\"): ", escape(input)); output = rfb::convertLF(input); - if (strcmp(output, expected) != 0) - printf("FAILED: got \"%s\"", escape(output)); + if (output != expected) + printf("FAILED: got \"%s\"", escape(output.c_str())); else printf("OK"); printf("\n"); fflush(stdout); - - rfb::strFree(output); } static void testCRLF(const char* input, const char* expected) { - char* output; + std::string output; printf("convertCRLF(\"%s\"): ", escape(input)); output = rfb::convertCRLF(input); - if (strcmp(output, expected) != 0) - printf("FAILED: got \"%s\"", escape(output)); + if (output != expected) + printf("FAILED: got \"%s\"", escape(output.c_str())); else printf("OK"); printf("\n"); fflush(stdout); - - rfb::strFree(output); } int main(int /*argc*/, char** /*argv*/) diff --git a/tests/unit/hostport.cxx b/tests/unit/hostport.cxx index 93ebc4c7..d82c3d51 100644 --- a/tests/unit/hostport.cxx +++ b/tests/unit/hostport.cxx @@ -27,23 +27,21 @@ static void doTest(const char* hostAndPort, const char* expectedHost, int expectedPort) { - char* host; + std::string host; int port; printf("\"%s\": ", hostAndPort); rfb::getHostAndPort(hostAndPort, &host, &port); - if (strcmp(host, expectedHost) != 0) - printf("FAILED (\"%s\" != \"%s\")", host, expectedHost); + if (host != expectedHost) + printf("FAILED (\"%s\" != \"%s\")", host.c_str(), expectedHost); else if (port != expectedPort) printf("FAILED (%d != %d)", port, expectedPort); else printf("OK"); printf("\n"); fflush(stdout); - - rfb::strFree(host); } int main(int /*argc*/, char** /*argv*/) diff --git a/tests/unit/unicode.cxx b/tests/unit/unicode.cxx index 0cd0f077..32452ee3 100644 --- a/tests/unit/unicode.cxx +++ b/tests/unit/unicode.cxx @@ -93,8 +93,8 @@ int main(int /*argc*/, char** /*argv*/) unsigned ucs4; char utf8[5]; wchar_t utf16[3]; - char *out; - wchar_t *wout; + std::string out; + std::wstring wout; size_t len; failures = 0; @@ -157,20 +157,18 @@ int main(int /*argc*/, char** /*argv*/) continue; out = rfb::latin1ToUTF8(latin1utf8[i].latin1); - if (strcmp(out, latin1utf8[i].utf8) != 0) { + if (out != latin1utf8[i].utf8) { printf("FAILED: latin1ToUTF8() #%d\n", (int)i+1); failures++; } - rfb::strFree(out); } for (i = 0;i < ARRAY_SIZE(latin1utf8);i++) { out = rfb::utf8ToLatin1(latin1utf8[i].utf8); - if (strcmp(out, latin1utf8[i].latin1) != 0) { + if (out != latin1utf8[i].latin1) { printf("FAILED: utf8ToLatin1() #%d\n", (int)i+1); failures++; } - rfb::strFree(out); } for (i = 0;i < ARRAY_SIZE(utf8utf16);i++) { @@ -179,11 +177,10 @@ int main(int /*argc*/, char** /*argv*/) continue; out = rfb::utf16ToUTF8(utf8utf16[i].utf16); - if (strcmp(out, utf8utf16[i].utf8) != 0) { + if (out != utf8utf16[i].utf8) { printf("FAILED: utf16ToUTF8() #%d\n", (int)i+1); failures++; } - rfb::strFree(out); } for (i = 0;i < ARRAY_SIZE(utf8utf16);i++) { @@ -192,11 +189,10 @@ int main(int /*argc*/, char** /*argv*/) continue; wout = rfb::utf8ToUTF16(utf8utf16[i].utf8); - if (wcscmp(wout, utf8utf16[i].utf16) != 0) { + if (wout != utf8utf16[i].utf16) { printf("FAILED: utf8ToUTF16() #%d\n", (int)i+1); failures++; } - rfb::strFree(wout); } if (failures == 0) { diff --git a/unix/xserver/hw/vnc/RFBGlue.cc b/unix/xserver/hw/vnc/RFBGlue.cc index 10393e68..4f63397e 100644 --- a/unix/xserver/hw/vnc/RFBGlue.cc +++ b/unix/xserver/hw/vnc/RFBGlue.cc @@ -113,9 +113,7 @@ int vncSetParamSimple(const char *nameAndValue) char* vncGetParam(const char *name) { - rfb::VoidParameter *param; - char *value; - char *ret; + VoidParameter *param; // Hack to avoid exposing password! if (strcasecmp(name, "Password") == 0) @@ -125,15 +123,7 @@ char* vncGetParam(const char *name) if (param == NULL) return NULL; - value = param->getValueStr(); - if (value == NULL) - return NULL; - - ret = strdup(value); - - delete [] value; - - return ret; + return strdup(param->getValueStr().c_str()); } const char* vncGetParamDesc(const char *name) @@ -234,7 +224,7 @@ int vncIsTCPPortUsed(int port) char* vncConvertLF(const char* src, size_t bytes) { try { - return convertLF(src, bytes); + return strDup(convertLF(src, bytes).c_str()); } catch (...) { return NULL; } @@ -243,7 +233,7 @@ char* vncConvertLF(const char* src, size_t bytes) char* vncLatin1ToUTF8(const char* src, size_t bytes) { try { - return latin1ToUTF8(src, bytes); + return strDup(latin1ToUTF8(src, bytes).c_str()); } catch (...) { return NULL; } @@ -252,7 +242,7 @@ char* vncLatin1ToUTF8(const char* src, size_t bytes) char* vncUTF8ToLatin1(const char* src, size_t bytes) { try { - return utf8ToLatin1(src, bytes); + return strDup(utf8ToLatin1(src, bytes).c_str()); } catch (...) { return NULL; } diff --git a/unix/xserver/hw/vnc/vncExtInit.cc b/unix/xserver/hw/vnc/vncExtInit.cc index 4c1fdd4d..0292a6d1 100644 --- a/unix/xserver/hw/vnc/vncExtInit.cc +++ b/unix/xserver/hw/vnc/vncExtInit.cc @@ -348,14 +348,13 @@ int vncConnectClient(const char *addr) return 0; } - char *host; + std::string host; int port; getHostAndPort(addr, &host, &port, 5500); try { - network::Socket* sock = new network::TcpSocket(host, port); - delete [] host; + network::Socket* sock = new network::TcpSocket(host.c_str(), port); desktop[0]->addClient(sock, true); } catch (rdr::Exception& e) { vlog.error("Reverse connection: %s",e.str()); diff --git a/vncviewer/CConn.cxx b/vncviewer/CConn.cxx index ef4252a7..780214f2 100644 --- a/vncviewer/CConn.cxx +++ b/vncviewer/CConn.cxx @@ -75,8 +75,7 @@ static const PixelFormat mediumColourPF(8, 8, false, true, static const unsigned bpsEstimateWindow = 1000; CConn::CConn(const char* vncServerName, network::Socket* socket=NULL) - : serverHost(0), serverPort(0), desktop(NULL), - updateCount(0), pixelCount(0), + : serverPort(0), desktop(NULL), updateCount(0), pixelCount(0), lastServerEncoding((unsigned int)-1), bpsEstimate(20000000) { setShared(::shared); @@ -98,15 +97,16 @@ CConn::CConn(const char* vncServerName, network::Socket* socket=NULL) #ifndef WIN32 if (strchr(vncServerName, '/') != NULL) { sock = new network::UnixSocket(vncServerName); - serverHost = strDup(sock->getPeerAddress()); - vlog.info(_("Connected to socket %s"), serverHost); + serverHost = sock->getPeerAddress(); + vlog.info(_("Connected to socket %s"), serverHost.c_str()); } else #endif { getHostAndPort(vncServerName, &serverHost, &serverPort); - sock = new network::TcpSocket(serverHost, serverPort); - vlog.info(_("Connected to host %s port %d"), serverHost, serverPort); + sock = new network::TcpSocket(serverHost.c_str(), serverPort); + vlog.info(_("Connected to host %s port %d"), + serverHost.c_str(), serverPort); } } catch (rdr::Exception& e) { vlog.error("%s", e.str()); @@ -118,7 +118,7 @@ CConn::CConn(const char* vncServerName, network::Socket* socket=NULL) Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this); - setServerName(serverHost); + setServerName(serverHost.c_str()); setStreams(&sock->inStream(), &sock->outStream()); initialiseProtocol(); @@ -136,7 +136,6 @@ CConn::~CConn() if (desktop) delete desktop; - delete [] serverHost; if (sock) Fl::remove_fd(sock->getFd()); delete sock; @@ -160,7 +159,7 @@ const char *CConn::connectionInfo() strcat(infoText, "\n"); snprintf(scratch, sizeof(scratch), - _("Host: %.80s port: %d"), serverHost, serverPort); + _("Host: %.80s port: %d"), serverHost.c_str(), serverPort); strcat(infoText, scratch); strcat(infoText, "\n"); diff --git a/vncviewer/CConn.h b/vncviewer/CConn.h index 4f0e86fe..0d8d7789 100644 --- a/vncviewer/CConn.h +++ b/vncviewer/CConn.h @@ -85,7 +85,7 @@ private: static void handleUpdateTimeout(void *data); private: - char* serverHost; + std::string serverHost; int serverPort; network::Socket* sock; diff --git a/vncviewer/DesktopWindow.cxx b/vncviewer/DesktopWindow.cxx index 3584845e..318e9f4e 100644 --- a/vncviewer/DesktopWindow.cxx +++ b/vncviewer/DesktopWindow.cxx @@ -1710,14 +1710,12 @@ void DesktopWindow::handleStatsTimeout(void *data) fl_draw(buffer, 5, statsHeight - 5); fl_color(FL_YELLOW); - siPrefix(self->stats[statsCount-1].pps, "pix/s", - buffer, sizeof(buffer), 3); - fl_draw(buffer, 5 + (statsWidth-10)/3, statsHeight - 5); + fl_draw(siPrefix(self->stats[statsCount-1].pps, "pix/s").c_str(), + 5 + (statsWidth-10)/3, statsHeight - 5); fl_color(FL_RED); - siPrefix(self->stats[statsCount-1].bps * 8, "bps", - buffer, sizeof(buffer), 3); - fl_draw(buffer, 5 + (statsWidth-10)*2/3, statsHeight - 5); + fl_draw(siPrefix(self->stats[statsCount-1].bps * 8, "bps").c_str(), + 5 + (statsWidth-10)*2/3, statsHeight - 5); image = surface->image(); delete surface; diff --git a/vncviewer/UserDialog.cxx b/vncviewer/UserDialog.cxx index ea5a8053..ff5b6123 100644 --- a/vncviewer/UserDialog.cxx +++ b/vncviewer/UserDialog.cxx @@ -34,7 +34,6 @@ #include #include -#include #include #include @@ -71,7 +70,8 @@ UserDialog::~UserDialog() { } -void UserDialog::getUserPasswd(bool secure, char** user, char** password) +void UserDialog::getUserPasswd(bool secure, std::string* user, + std::string* password) { const char *passwordFileName(passwordFile); @@ -80,13 +80,13 @@ void UserDialog::getUserPasswd(bool secure, char** user, char** password) char *envPassword = getenv("VNC_PASSWORD"); if(user && envUsername && envPassword) { - *user = strdup(envUsername); - *password = strdup(envPassword); + *user = envUsername; + *password = envPassword; return; } if (!user && envPassword) { - *password = strdup(envPassword); + *password = envPassword; return; } @@ -102,7 +102,7 @@ void UserDialog::getUserPasswd(bool secure, char** user, char** password) fclose(fp); PlainPasswd passwd(obfPwd); - *password = passwd.takeBuf(); + *password = passwd.buf; return; } @@ -198,8 +198,8 @@ void UserDialog::getUserPasswd(bool secure, char** user, char** password) if (ret_val == 0) { if (user) - *user = strDup(username->value()); - *password = strDup(passwd->value()); + *user = username->value(); + *password = passwd->value(); } delete win; diff --git a/vncviewer/UserDialog.h b/vncviewer/UserDialog.h index b62ba7f3..913af841 100644 --- a/vncviewer/UserDialog.h +++ b/vncviewer/UserDialog.h @@ -31,7 +31,8 @@ public: // UserPasswdGetter callbacks - void getUserPasswd(bool secure, char** user, char** password); + void getUserPasswd(bool secure, std::string* user, + std::string* password); // UserMsgBox callbacks diff --git a/vncviewer/Viewport.cxx b/vncviewer/Viewport.cxx index c12394ab..66903c5f 100644 --- a/vncviewer/Viewport.cxx +++ b/vncviewer/Viewport.cxx @@ -560,7 +560,7 @@ void Viewport::resize(int x, int y, int w, int h) int Viewport::handle(int event) { - char *filtered; + std::string filtered; int buttonMask, wheelMask; DownMap::const_iterator iter; @@ -568,17 +568,15 @@ int Viewport::handle(int event) case FL_PASTE: filtered = convertLF(Fl::event_text(), Fl::event_length()); - vlog.debug("Sending clipboard data (%d bytes)", (int)strlen(filtered)); + vlog.debug("Sending clipboard data (%d bytes)", (int)filtered.size()); try { - cc->sendClipboardData(filtered); + cc->sendClipboardData(filtered.c_str()); } catch (rdr::Exception& e) { vlog.error("%s", e.str()); abort_connection_with_unexpected_error(e); } - strFree(filtered); - return 1; case FL_ENTER: diff --git a/win/rfb_win32/Clipboard.cxx b/win/rfb_win32/Clipboard.cxx index 9a9dfb6a..d90d0b7a 100644 --- a/win/rfb_win32/Clipboard.cxx +++ b/win/rfb_win32/Clipboard.cxx @@ -86,11 +86,11 @@ Clipboard::processMessage(UINT msg, WPARAM wParam, LPARAM lParam) { return MsgWindow::processMessage(msg, wParam, lParam); }; -char* +std::string Clipboard::getClipText() { HGLOBAL cliphandle; wchar_t* clipdata; - CharArray utf8; + std::string utf8; // Open the clipboard if (!OpenClipboard(getHandle())) @@ -110,13 +110,13 @@ Clipboard::getClipText() { } // Convert it to UTF-8 - utf8.replaceBuf(utf16ToUTF8(clipdata)); + utf8 = utf16ToUTF8(clipdata); // Release the buffer and close the clipboard GlobalUnlock(cliphandle); CloseClipboard(); - return convertLF(utf8.buf); + return convertLF(utf8.c_str()); } void @@ -130,20 +130,16 @@ Clipboard::setClipText(const char* text) { throw rdr::SystemException("unable to open Win32 clipboard", GetLastError()); // - Convert the supplied clipboard text into UTF-16 format with CRLF - CharArray filtered(convertCRLF(text)); - wchar_t* utf16; - - utf16 = utf8ToUTF16(filtered.buf); + std::string filtered(convertCRLF(text)); + std::wstring utf16(utf8ToUTF16(filtered.c_str())); // - Allocate global memory for the data - clip_handle = ::GlobalAlloc(GMEM_MOVEABLE, (wcslen(utf16) + 1) * 2); + clip_handle = ::GlobalAlloc(GMEM_MOVEABLE, (utf16.size() + 1) * 2); wchar_t* data = (wchar_t*) GlobalLock(clip_handle); - wcscpy(data, utf16); + wcscpy(data, utf16.c_str()); GlobalUnlock(clip_handle); - strFree(utf16); - // - Next, we must clear out any existing data if (!EmptyClipboard()) throw rdr::SystemException("unable to empty Win32 clipboard", GetLastError()); diff --git a/win/rfb_win32/Clipboard.h b/win/rfb_win32/Clipboard.h index 1dead82e..588f1086 100644 --- a/win/rfb_win32/Clipboard.h +++ b/win/rfb_win32/Clipboard.h @@ -50,7 +50,7 @@ namespace rfb { void setNotifier(Notifier* cbn) {notifier = cbn;} // - Get the clipboard contents - char* getClipText(); + std::string getClipText(); // - Set the clipboard contents void setClipText(const char* text); diff --git a/win/rfb_win32/RegConfig.cxx b/win/rfb_win32/RegConfig.cxx index 73a9e699..38ca52f9 100644 --- a/win/rfb_win32/RegConfig.cxx +++ b/win/rfb_win32/RegConfig.cxx @@ -26,7 +26,6 @@ #include #include -#include //#include using namespace rfb; @@ -63,8 +62,8 @@ void RegConfig::loadRegistryConfig(RegKey& key) { while (1) { const char *name = key.getValueName(i++); if (!name) break; - CharArray value(key.getRepresentation(name)); - if (!value.buf || !Configuration::setParam(name, value.buf)) + std::string value = key.getRepresentation(name); + if (!Configuration::setParam(name, value.c_str())) vlog.info("unable to process %s", name); } } catch (rdr::SystemException& e) { diff --git a/win/rfb_win32/Registry.cxx b/win/rfb_win32/Registry.cxx index a994fe6f..dccaa727 100644 --- a/win/rfb_win32/Registry.cxx +++ b/win/rfb_win32/Registry.cxx @@ -164,18 +164,21 @@ void RegKey::setBool(const char* valname, bool value) const { setInt(valname, value ? 1 : 0); } -char* RegKey::getString(const char* valname) const {return getRepresentation(valname);} -char* RegKey::getString(const char* valname, const char* def) const { +std::string RegKey::getString(const char* valname) const { + return getRepresentation(valname); +} + +std::string RegKey::getString(const char* valname, const char* def) const { try { return getString(valname); } catch(rdr::Exception&) { - return strDup(def); + return def; } } std::vector RegKey::getBinary(const char* valname) const { - CharArray hex(getRepresentation(valname)); - return hexToBin(hex.buf, strlen(hex.buf)); + std::string hex = getRepresentation(valname); + return hexToBin(hex.data(), hex.size()); } std::vector RegKey::getBinary(const char* valname, const uint8_t* def, size_t deflen) const { try { @@ -188,8 +191,7 @@ std::vector RegKey::getBinary(const char* valname, const uint8_t* def, } int RegKey::getInt(const char* valname) const { - CharArray tmp(getRepresentation(valname)); - return atoi(tmp.buf); + return atoi(getRepresentation(valname).c_str()); } int RegKey::getInt(const char* valname, int def) const { try { @@ -206,17 +208,7 @@ bool RegKey::getBool(const char* valname, bool def) const { return getInt(valname, def ? 1 : 0) > 0; } -static inline char* terminateData(char* data, int length) -{ - // We must terminate the string, just to be sure. Stupid Win32... - int len = length/sizeof(char); - CharArray str(len+1); - memcpy(str.buf, data, length); - str.buf[len] = 0; - return str.takeBuf(); -} - -char* RegKey::getRepresentation(const char* valname) const { +std::string RegKey::getRepresentation(const char* valname) const { DWORD type, length; LONG result = RegQueryValueEx(key, valname, 0, &type, 0, &length); if (result != ERROR_SUCCESS) @@ -229,35 +221,34 @@ char* RegKey::getRepresentation(const char* valname) const { switch (type) { case REG_BINARY: { - CharArray hex(binToHex((const uint8_t*)data.buf, length)); - return hex.takeBuf(); + return binToHex((const uint8_t*)data.buf, length); } case REG_SZ: if (length) { - return terminateData(data.buf, length); + return std::string(data.buf, length); } else { - return strDup(""); + return ""; } case REG_DWORD: { - CharArray tmp(16); - sprintf(tmp.buf, "%lu", *((DWORD*)data.buf)); - return tmp.takeBuf(); + char tmp[16]; + sprintf(tmp, "%lu", *((DWORD*)data.buf)); + return tmp; } case REG_EXPAND_SZ: { if (length) { - CharArray str(terminateData(data.buf, length)); - DWORD required = ExpandEnvironmentStrings(str.buf, 0, 0); + std::string str(data.buf, length); + DWORD required = ExpandEnvironmentStrings(str.c_str(), 0, 0); if (required==0) throw rdr::SystemException("ExpandEnvironmentStrings", GetLastError()); CharArray result(required); - length = ExpandEnvironmentStrings(str.buf, result.buf, required); + length = ExpandEnvironmentStrings(str.c_str(), result.buf, required); if (required getBinary(const char* valname) const; std::vector getBinary(const char* valname, const uint8_t* def, size_t deflength) const; @@ -87,7 +87,7 @@ namespace rfb { bool getBool(const char* valname) const; bool getBool(const char* valname, bool def) const; - char* getRepresentation(const char* valname) const; + std::string getRepresentation(const char* valname) const; bool isValue(const char* valname) const; diff --git a/win/rfb_win32/SDisplay.cxx b/win/rfb_win32/SDisplay.cxx index 110edcb0..811b1033 100644 --- a/win/rfb_win32/SDisplay.cxx +++ b/win/rfb_win32/SDisplay.cxx @@ -296,8 +296,7 @@ void SDisplay::restartCore() { void SDisplay::handleClipboardRequest() { - CharArray data(clipboard->getClipText()); - server->sendClipboardData(data.buf); + server->sendClipboardData(clipboard->getClipText().c_str()); } void SDisplay::handleClipboardAnnounce(bool available) { diff --git a/win/rfb_win32/Win32Util.cxx b/win/rfb_win32/Win32Util.cxx index 53443007..5f0bdbc7 100644 --- a/win/rfb_win32/Win32Util.cxx +++ b/win/rfb_win32/Win32Util.cxx @@ -67,9 +67,9 @@ const char* FileVersionInfo::getVerString(const char* name, DWORD langId) { langId = langId >> 8; } - CharArray langIdStr(binToHex(langIdBuf, sizeof(langId))); - CharArray infoName(strlen("StringFileInfo") + 4 + strlen(name) + strlen(langIdStr.buf)); - sprintf(infoName.buf, "\\StringFileInfo\\%s\\%s", langIdStr.buf, name); + 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); // Locate the required version string within the version info char* buffer = 0; diff --git a/win/vncconfig/Authentication.h b/win/vncconfig/Authentication.h index 6789a4f2..cc162077 100644 --- a/win/vncconfig/Authentication.h +++ b/win/vncconfig/Authentication.h @@ -93,8 +93,8 @@ namespace rfb { #ifdef HAVE_GNUTLS if (isItemChecked(IDC_ENC_X509)) { - SSecurityTLS::X509_CertFile.setParam(regKey.getString("X509Cert")); - SSecurityTLS::X509_CertFile.setParam(regKey.getString("X509Key")); + SSecurityTLS::X509_CertFile.setParam(regKey.getString("X509Cert").c_str()); + SSecurityTLS::X509_CertFile.setParam(regKey.getString("X509Key").c_str()); } #endif diff --git a/win/vncconfig/Connections.h b/win/vncconfig/Connections.h index fbf46ec1..f9b66547 100644 --- a/win/vncconfig/Connections.h +++ b/win/vncconfig/Connections.h @@ -73,7 +73,7 @@ namespace rfb { try { network::TcpFilter::Pattern pat(network::TcpFilter::parsePattern(newPat.buf)); - pattern.replaceBuf(CharArray(network::TcpFilter::patternToStr(pat)).takeBuf()); + pattern.replaceBuf(strDup(network::TcpFilter::patternToStr(pat).c_str())); } catch(rdr::Exception& e) { MsgBox(NULL, e.str(), MB_ICONEXCLAMATION | MB_OK); return false; @@ -101,7 +101,7 @@ namespace rfb { SendMessage(listBox, LB_DELETESTRING, 0, 0); CharArray tmp; - tmp.buf = hosts.getData(); + tmp.buf = strDup(hosts.getValueStr().c_str()); while (tmp.buf) { CharArray first; strSplit(tmp.buf, ',', &first.buf, &tmp.buf); @@ -228,13 +228,13 @@ namespace rfb { regKey.setInt("PortNumber", isItemChecked(IDC_RFB_ENABLE) ? getItemInt(IDC_PORT) : 0); regKey.setInt("IdleTimeout", getItemInt(IDC_IDLE_TIMEOUT)); regKey.setInt("LocalHost", isItemChecked(IDC_LOCALHOST)); - regKey.setString("Hosts", CharArray(getHosts()).buf); + regKey.setString("Hosts", getHosts().c_str()); return true; } bool isChanged() { try { - CharArray new_hosts(getHosts()); - return (strcmp(new_hosts.buf, hosts) != 0) || + std::string new_hosts = getHosts(); + return (new_hosts != (const char*)hosts) || (localHost != isItemChecked(IDC_LOCALHOST)) || (port_number != getItemInt(IDC_PORT)) || (rfb::Server::idleTimeout != getItemInt(IDC_IDLE_TIMEOUT)); @@ -242,21 +242,21 @@ namespace rfb { return false; } } - char* getHosts() { + std::string getHosts() { int bufLen = 1, i; HWND listBox = GetDlgItem(handle, IDC_HOSTS); for (i=0; i hosts_str(bufLen); + hosts_str[0] = 0; + char* outPos = hosts_str.data(); for (i=0; i addrs; + std::list addrs; if (rfbSock.isListening()) - TcpListener::getMyAddresses(&addrs); + addrs = TcpListener::getMyAddresses(); else - addrs.push_front(strDup("Not accepting connections")); + addrs.push_front("Not accepting connections"); // Allocate space for the new tip - std::list::iterator i, next_i; + std::list::iterator i, next_i; int length = strlen(prefix)+1; for (i=addrs.begin(); i!= addrs.end(); i++) - length += strlen(*i) + 1; + length += i->size() + 1; // Build the new tip CharArray toolTip(length); strcpy(toolTip.buf, prefix); for (i=addrs.begin(); i!= addrs.end(); i=next_i) { next_i = i; next_i ++; - CharArray addr(*i); // Assumes ownership of string - strcat(toolTip.buf, addr.buf); + strcat(toolTip.buf, i->c_str()); if (next_i != addrs.end()) strcat(toolTip.buf, ","); } @@ -230,11 +229,11 @@ bool VNCServerWin32::disconnectClients(const char* reason) { bool VNCServerWin32::addNewClient(const char* client) { TcpSocket* sock = 0; try { - CharArray hostname; + std::string hostname; int port; - getHostAndPort(client, &hostname.buf, &port, 5500); + getHostAndPort(client, &hostname, &port, 5500); vlog.error("port=%d", port); - sock = new TcpSocket(hostname.buf, port); + sock = new TcpSocket(hostname.c_str(), port); if (queueCommand(AddClient, sock, 0)) return true; delete sock;