| 23 | } |
| 24 | |
| 25 | bool MessageTcp::readMessage(std::vector<char> &message) { |
| 26 | message.clear(); |
| 27 | think(); |
| 28 | |
| 29 | const char *buffer = inputBuffer.data() + inputPos; |
| 30 | auto remains = inputBuffer.size() - inputPos; |
| 31 | auto pull = [&](void* ptr, std::size_t size) -> void { |
| 32 | assert(size <= remains); |
| 33 | memcpy(ptr, buffer, size); |
| 34 | buffer += size; |
| 35 | remains -= size; |
| 36 | }; |
| 37 | |
| 38 | if (remains < 12) |
| 39 | return false; |
| 40 | int len = -1; |
| 41 | char magic[5] = {0}; |
| 42 | |
| 43 | //note: little-endianness is assumed |
| 44 | pull(magic, 4); |
| 45 | if (strcmp(magic, "TDM[") != 0) |
| 46 | goto zomg; |
| 47 | pull(&len, 4); |
| 48 | if (len < 0) |
| 49 | goto zomg; |
| 50 | pull(magic, 4); |
| 51 | if (strcmp(magic, "] ") != 0) |
| 52 | goto zomg; |
| 53 | |
| 54 | if (remains < static_cast<std::size_t>(len) + 12) |
| 55 | return false; |
| 56 | |
| 57 | message.reserve(len + 1); |
| 58 | message.resize(len); |
| 59 | pull(message.data(), len); |
| 60 | message.data()[len] = '\0'; |
| 61 | |
| 62 | pull(magic, 4); |
| 63 | if (strcmp(magic, " (") != 0) |
| 64 | goto zomg; |
| 65 | int len2; |
| 66 | pull(&len2, 4); |
| 67 | if (len2 != len) |
| 68 | goto zomg; |
| 69 | pull(magic, 4); |
| 70 | if (strcmp(magic, ")TDM") != 0) |
| 71 | goto zomg; |
| 72 | |
| 73 | inputPos = buffer - inputBuffer.data(); |
| 74 | return true; |
| 75 | |
| 76 | zomg: |
| 77 | rError() << "ERROR: MessageTCP: wrong message format\n"; |
| 78 | message.clear(); |
| 79 | init({}); |
| 80 | return false; |
| 81 | } |
| 82 | |