I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it. Here is my first try. Now I need to get review for my new code.
void sslWrite(SSL *ssl, const void *buf, unsigned size)
{
int writedTotal = 0;
const char *ccBuf = reinterpret_cast<const char *>(buf);
while (writedTotal < size) {
int writedPart = SSL_write(ssl, ccBuf + writedTotal, size - writedTotal);
if (writedPart < 0) {
std::string error = "SSL_write error = ";
error += (std::to_string(writedPart) + ".");
throw std::runtime_error(error);
}
writedTotal += writedPart;
}
}
std::vector<char> sslRead(SSL *ssl, unsigned size)
{
std::vector<char> ret(size);
unsigned readTotal = 0;
while (readTotal < size) {
int readPart = SSL_read(ssl, &ret[readTotal], size - readTotal);
if (readPart < 0) {
std::string error = "SSL_read error = ";
error += (std::to_string(readPart) + ".");
throw std::runtime_error(error);
}
readTotal += readPart;
}
return ret;
}
void sslWriteSize(SSL *ssl, unsigned size)
{
if (sizeof(u_long) > 8)
throw std::runtime_error("Write size error.");
u_long nlSize = htonl(size);
sslWrite(ssl, &nlSize, 8);
}
unsigned sslReadSize(SSL *ssl)
{
if (sizeof(u_long) > 8)
throw std::runtime_error("Read size error.");
u_long size = *reinterpret_cast<u_long *>(&sslRead(ssl, 8)[0]);
size = ntohl(size);
return size;
}
void sslWrite(SSL *ssl, const std::string &data)
{
if (data.empty())
throw std::runtime_error("SSL write error. Data is empty.");
sslWriteSize(ssl, data.size());
sslWrite(ssl, &data.at(0), data.size());
}
std::vector<char> sslRead(SSL *ssl)
{
unsigned size = sslReadSize(ssl);
return sslRead(ssl, size);
}
Is there a buffering problem as in my old code?