int FileTransferProtocol::recvFilename(net::Socket &s, string &filename) { int bytes_received; // First, receive the filename size (3 bytes ascii-encoded unsigned integer) char buf[3]; bytes_received = s.recv(buf, 3, 0); if (bytes_received == SOCKET_ERROR || bytes_received != 3) { onTransferError("Could not receive filename header size!"); return -1; } // Try to parse what we have received size_t len; if (EOF == sscanf_s(buf, "%3lu", &len)) { onTransferError("Could not parse filename header size!"); return -1; } // Finally, allocate a string and receive the filename char *nameBuf = (char*)malloc(len + 1); nameBuf[len] = '\0'; bytes_received = s.recv(nameBuf, len, 0); if (bytes_received == SOCKET_ERROR || bytes_received != len) { free(nameBuf); onTransferError("Could not receive filename header!"); } filename = string(nameBuf); free(nameBuf); return 0; }
int FileTransferProtocol::waitForAck(net::Socket &s, string errmsg) { char ackbuf[4] = " "; // Either ACK or ERR int bytes_received = s.recv(ackbuf, 3, 0); if (bytes_received == SOCKET_ERROR || bytes_received != 3 || strcmp(ackbuf, "ERR") == 0) { onTransferError(errmsg); return -1; } return 0; }
int FileTransferProtocol::recvCommand(net::Socket &s, char &command) { char d; int bytes_received; bytes_received = s.recv(&d, 1, 0); if (bytes_received == SOCKET_ERROR || bytes_received != 1) { onTransferError("Could not receive direction from client!"); return -1; } if (d != 'D' && d != 'U' && d != 'L' && d != 'Q') { onTransferError("Client sent invalid direction!"); return -1; } command = d; return 0; }
size_t StreamSocketReceiver::receiveHeader(net::Socket &s) { char buf[20]; size_t bytes_received; if (bytes_received = s.recv(buf, 20) != 20) { throw IncompleteReceiveException(bytes_received, 20); } // Try to parse length of payload in header size_t len; if (EOF == sscanf_s(buf, "%20lu", &len)) { throw UnparseableHeaderException(buf); } return len; }
void StreamSocketReceiver::receivePayload(net::Socket &s, ostream &stream, size_t len) { void *buf = malloc(this->packet_size); size_t bytes_read = 0; while (bytes_read < len) { size_t exp_bytes = min(this->packet_size, len - bytes_read); size_t bytes_recv = s.recv((char*)buf, exp_bytes); if (bytes_recv != exp_bytes) { free(buf); throw IncompleteReceiveException(bytes_read + bytes_recv, len); } bytes_read += bytes_recv; stream.write((char*)buf, bytes_recv); } free(buf); }