Issue 22: Convert remaining code to use the log module
[remote/remote-mci.git] / protocols / Message.cc
blob5febc2becf1bfe740c8035b9239a597a618799d4
1 #include "Message.h"
3 namespace remote { namespace protocols {
5 Message::Message()
7 data = NULL;
8 datalen = 0;
9 recvLen = 0;
12 Message::~Message()
14 if (data) delete data;
15 datalen = 0;
18 bool Message::nonBlockingRecv(int fd)
20 char* p_datalen = (char*)&datalen;
21 int r;
22 uint32_t targetRecvLen;
24 if ( recvLen < sizeof(datalen))
26 // still at the datalen part
27 r = read(fd,p_datalen+recvLen,sizeof(datalen)-recvLen);
28 if (r <= 0) {
29 Log::error("Recv error: %s", strerror(errno));
30 __THROW__("Unable to read message length!");
32 recvLen += r;
34 if ( recvLen < sizeof(datalen) )
36 return false;
38 if ( recvLen == sizeof(datalen) )
40 datalen = ntohl(datalen);
41 if (datalen > 512000) __THROW__("Data too long!");
42 if (data) delete data;
43 data = new uint8_t[datalen];
45 targetRecvLen = datalen + sizeof(datalen);
46 if ( recvLen >= sizeof(datalen) && recvLen < targetRecvLen )
48 r = read(fd,data+recvLen-sizeof(datalen),targetRecvLen-recvLen);
49 if (r <= 0) {
50 Log::error("Recv error: %s", strerror(errno));
51 __THROW__ ("Unable to read message data!");
53 recvLen += r;
54 // printf("Read %u of %u bytes.\n",recvLen-sizeof(datalen),datalen);
56 if (recvLen == targetRecvLen)
58 recvLen = 0;
59 return true;
61 return false;
65 void Message::sendMsg(int fd,BaseMsg& msg)
67 uint32_t len;
68 if (data) delete data;
69 // allocate data
70 datalen = msg.getLength();
71 data = new uint8_t[datalen];
72 len = datalen;
73 // printf("Writing %u bytes of message data\n",datalen);
75 uint8_t* d = data;
76 msg.write(d,len);
77 // msg.print(stdout);
80 // write length, then data
81 if (!send(fd,datalen))
82 __THROW__ ("Unable to send datalen!");
83 if (::send(fd, (char*)data, datalen, 0) != ((int64_t)datalen))
84 __THROW__ ("Unable to send data!");
85 // printf("Done writing %u bytes of message data\n\n\n",datalen);
88 uint32_t Message::getLength()
90 return datalen;
93 uint8_t* Message::getData()
95 return data;