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.
int sslWrite(SSL *ssl, const std::string &data)
{
return sslWrite(ssl, &data[0], data.size());
}
int sslWrite(SSL *ssl, const void *buf, unsigned num)
{
const int INT_SIZE = sizeof(int);
const int numv = INT_SIZE + num;
std::vector<char> bufv(numv);
memcpy(&bufv[0], &numv, INT_SIZE);
if (num != 0) {
memcpy(&bufv[INT_SIZE], buf, num);
}
int n = 0;
while (n < num) {
int w = SSL_write(ssl, &bufv[0], numv - n);
if (w < 0) {
return 0;
}
n += w;
}
return n;
}
const int BUF_INIT_SIZE = 0x10000;
std::vector<char> sslRead(SSL *ssl)
{
const int INT_SIZE = sizeof(int);
std::vector<char> bufv(BUF_INIT_SIZE);
int m = SSL_read(ssl, &bufv.at(0), BUF_INIT_SIZE);
if (m == 0) {
return std::vector<char>();
}
if (m < 0) {
throw std::runtime_error("m < 0");
}
const int n = *reinterpret_cast<int *>(&bufv[0]);
bufv.resize(n);
while (m < n) {
int k = SSL_read(ssl, &bufv.at(m), n - m);
if (k < 0) {
throw std::runtime_error("k < 0");
}
m += k;
}
bufv.resize(m);
if (m < INT_SIZE) {
throw std::runtime_error("m < INT_SIZE");
}
bufv.erase(bufv.begin(), bufv.begin() + INT_SIZE);
return bufv;
}