redis_reply.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #include <limits>
  18. #include "butil/logging.h"
  19. #include "butil/string_printf.h"
  20. #include "brpc/redis_reply.h"
  21. namespace brpc {
  22. //BAIDU_CASSERT(sizeof(RedisReply) == 24, size_match);
  23. const int RedisReply::npos = -1;
  24. const char* RedisReplyTypeToString(RedisReplyType type) {
  25. switch (type) {
  26. case REDIS_REPLY_STRING: return "string";
  27. case REDIS_REPLY_ARRAY: return "array";
  28. case REDIS_REPLY_INTEGER: return "integer";
  29. case REDIS_REPLY_NIL: return "nil";
  30. case REDIS_REPLY_STATUS: return "status";
  31. case REDIS_REPLY_ERROR: return "error";
  32. default: return "unknown redis type";
  33. }
  34. }
  35. bool RedisReply::SerializeTo(butil::IOBufAppender* appender) {
  36. switch (_type) {
  37. case REDIS_REPLY_ERROR:
  38. // fall through
  39. case REDIS_REPLY_STATUS:
  40. appender->push_back((_type == REDIS_REPLY_ERROR)? '-' : '+');
  41. if (_length < (int)sizeof(_data.short_str)) {
  42. appender->append(_data.short_str, _length);
  43. } else {
  44. appender->append(_data.long_str, _length);
  45. }
  46. appender->append("\r\n", 2);
  47. return true;
  48. case REDIS_REPLY_INTEGER:
  49. appender->push_back(':');
  50. appender->append_decimal(_data.integer);
  51. appender->append("\r\n", 2);
  52. return true;
  53. case REDIS_REPLY_STRING:
  54. appender->push_back('$');
  55. appender->append_decimal(_length);
  56. appender->append("\r\n", 2);
  57. if (_length != npos) {
  58. if (_length < (int)sizeof(_data.short_str)) {
  59. appender->append(_data.short_str, _length);
  60. } else {
  61. appender->append(_data.long_str, _length);
  62. }
  63. appender->append("\r\n", 2);
  64. }
  65. return true;
  66. case REDIS_REPLY_ARRAY:
  67. appender->push_back('*');
  68. appender->append_decimal(_length);
  69. appender->append("\r\n", 2);
  70. if (_length != npos) {
  71. for (int i = 0; i < _length; ++i) {
  72. if (!_data.array.replies[i].SerializeTo(appender)) {
  73. return false;
  74. }
  75. }
  76. }
  77. return true;
  78. case REDIS_REPLY_NIL:
  79. LOG(ERROR) << "Do you forget to call SetXXX()?";
  80. return false;
  81. }
  82. CHECK(false) << "unknown redis type=" << _type;
  83. return false;
  84. }
  85. ParseError RedisReply::ConsumePartialIOBuf(butil::IOBuf& buf) {
  86. if (_type == REDIS_REPLY_ARRAY && _data.array.last_index >= 0) {
  87. // The parsing was suspended while parsing sub replies,
  88. // continue the parsing.
  89. RedisReply* subs = (RedisReply*)_data.array.replies;
  90. for (int i = _data.array.last_index; i < _length; ++i) {
  91. ParseError err = subs[i].ConsumePartialIOBuf(buf);
  92. if (err != PARSE_OK) {
  93. return err;
  94. }
  95. ++_data.array.last_index;
  96. }
  97. // We've got an intact reply. reset the index.
  98. _data.array.last_index = -1;
  99. return PARSE_OK;
  100. }
  101. // Notice that all branches returning PARSE_ERROR_NOT_ENOUGH_DATA must not change `buf'.
  102. const char* pfc = (const char*)buf.fetch1();
  103. if (pfc == NULL) {
  104. return PARSE_ERROR_NOT_ENOUGH_DATA;
  105. }
  106. const char fc = *pfc; // first character
  107. switch (fc) {
  108. case '-': // Error "-<message>\r\n"
  109. case '+': { // Simple String "+<string>\r\n"
  110. butil::IOBuf str;
  111. if (buf.cut_until(&str, "\r\n") != 0) {
  112. const size_t len = buf.size();
  113. if (len > std::numeric_limits<uint32_t>::max()) {
  114. LOG(ERROR) << "simple string is too long! max length=2^32-1,"
  115. " actually=" << len;
  116. return PARSE_ERROR_ABSOLUTELY_WRONG;
  117. }
  118. return PARSE_ERROR_NOT_ENOUGH_DATA;
  119. }
  120. const size_t len = str.size() - 1;
  121. if (len < sizeof(_data.short_str)) {
  122. // SSO short strings, including empty string.
  123. _type = (fc == '-' ? REDIS_REPLY_ERROR : REDIS_REPLY_STATUS);
  124. _length = len;
  125. str.copy_to_cstr(_data.short_str, (size_t)-1L, 1/*skip fc*/);
  126. return PARSE_OK;
  127. }
  128. char* d = (char*)_arena->allocate((len/8 + 1)*8);
  129. if (d == NULL) {
  130. LOG(FATAL) << "Fail to allocate string[" << len << "]";
  131. return PARSE_ERROR_ABSOLUTELY_WRONG;
  132. }
  133. CHECK_EQ(len, str.copy_to_cstr(d, (size_t)-1L, 1/*skip fc*/));
  134. _type = (fc == '-' ? REDIS_REPLY_ERROR : REDIS_REPLY_STATUS);
  135. _length = len;
  136. _data.long_str = d;
  137. return PARSE_OK;
  138. }
  139. case '$': // Bulk String "$<length>\r\n<string>\r\n"
  140. case '*': // Array "*<size>\r\n<sub-reply1><sub-reply2>..."
  141. case ':': { // Integer ":<integer>\r\n"
  142. char intbuf[32]; // enough for fc + 64-bit decimal + \r\n
  143. const size_t ncopied = buf.copy_to(intbuf, sizeof(intbuf) - 1);
  144. intbuf[ncopied] = '\0';
  145. const size_t crlf_pos = butil::StringPiece(intbuf, ncopied).find("\r\n");
  146. if (crlf_pos == butil::StringPiece::npos) { // not enough data
  147. return PARSE_ERROR_NOT_ENOUGH_DATA;
  148. }
  149. char* endptr = NULL;
  150. int64_t value = strtoll(intbuf + 1/*skip fc*/, &endptr, 10);
  151. if (endptr != intbuf + crlf_pos) {
  152. LOG(ERROR) << '`' << intbuf + 1 << "' is not a valid 64-bit decimal";
  153. return PARSE_ERROR_ABSOLUTELY_WRONG;
  154. }
  155. if (fc == ':') {
  156. buf.pop_front(crlf_pos + 2/*CRLF*/);
  157. _type = REDIS_REPLY_INTEGER;
  158. _length = 0;
  159. _data.integer = value;
  160. return PARSE_OK;
  161. } else if (fc == '$') {
  162. const int64_t len = value; // `value' is length of the string
  163. if (len < 0) { // redis nil
  164. buf.pop_front(crlf_pos + 2/*CRLF*/);
  165. _type = REDIS_REPLY_NIL;
  166. _length = 0;
  167. _data.integer = 0;
  168. return PARSE_OK;
  169. }
  170. if (len > (int64_t)std::numeric_limits<uint32_t>::max()) {
  171. LOG(ERROR) << "bulk string is too long! max length=2^32-1,"
  172. " actually=" << len;
  173. return PARSE_ERROR_ABSOLUTELY_WRONG;
  174. }
  175. // We provide c_str(), thus even if bulk string is started with
  176. // length, we have to end it with \0.
  177. if (buf.size() < crlf_pos + 2 + (size_t)len + 2/*CRLF*/) {
  178. return PARSE_ERROR_NOT_ENOUGH_DATA;
  179. }
  180. if ((size_t)len < sizeof(_data.short_str)) {
  181. // SSO short strings, including empty string.
  182. _type = REDIS_REPLY_STRING;
  183. _length = len;
  184. buf.pop_front(crlf_pos + 2);
  185. buf.cutn(_data.short_str, len);
  186. _data.short_str[len] = '\0';
  187. } else {
  188. char* d = (char*)_arena->allocate((len/8 + 1)*8);
  189. if (d == NULL) {
  190. LOG(FATAL) << "Fail to allocate string[" << len << "]";
  191. return PARSE_ERROR_ABSOLUTELY_WRONG;
  192. }
  193. buf.pop_front(crlf_pos + 2/*CRLF*/);
  194. buf.cutn(d, len);
  195. d[len] = '\0';
  196. _type = REDIS_REPLY_STRING;
  197. _length = len;
  198. _data.long_str = d;
  199. }
  200. char crlf[2];
  201. buf.cutn(crlf, sizeof(crlf));
  202. if (crlf[0] != '\r' || crlf[1] != '\n') {
  203. LOG(ERROR) << "Bulk string is not ended with CRLF";
  204. return PARSE_ERROR_ABSOLUTELY_WRONG;
  205. }
  206. return PARSE_OK;
  207. } else {
  208. const int64_t count = value; // `value' is count of sub replies
  209. if (count < 0) { // redis nil
  210. buf.pop_front(crlf_pos + 2/*CRLF*/);
  211. _type = REDIS_REPLY_NIL;
  212. _length = 0;
  213. _data.integer = 0;
  214. return PARSE_OK;
  215. }
  216. if (count == 0) { // empty array
  217. buf.pop_front(crlf_pos + 2/*CRLF*/);
  218. _type = REDIS_REPLY_ARRAY;
  219. _length = 0;
  220. _data.array.last_index = -1;
  221. _data.array.replies = NULL;
  222. return PARSE_OK;
  223. }
  224. if (count > (int64_t)std::numeric_limits<uint32_t>::max()) {
  225. LOG(ERROR) << "Too many sub replies! max count=2^32-1,"
  226. " actually=" << count;
  227. return PARSE_ERROR_ABSOLUTELY_WRONG;
  228. }
  229. // FIXME(gejun): Call allocate_aligned instead.
  230. RedisReply* subs = (RedisReply*)_arena->allocate(sizeof(RedisReply) * count);
  231. if (subs == NULL) {
  232. LOG(FATAL) << "Fail to allocate RedisReply[" << count << "]";
  233. return PARSE_ERROR_ABSOLUTELY_WRONG;
  234. }
  235. for (int64_t i = 0; i < count; ++i) {
  236. new (&subs[i]) RedisReply(_arena);
  237. }
  238. buf.pop_front(crlf_pos + 2/*CRLF*/);
  239. _type = REDIS_REPLY_ARRAY;
  240. _length = count;
  241. _data.array.replies = subs;
  242. // Recursively parse sub replies. If any of them fails, it will
  243. // be continued in next calls by tracking _data.array.last_index.
  244. _data.array.last_index = 0;
  245. for (int64_t i = 0; i < count; ++i) {
  246. ParseError err = subs[i].ConsumePartialIOBuf(buf);
  247. if (err != PARSE_OK) {
  248. return err;
  249. }
  250. ++_data.array.last_index;
  251. }
  252. _data.array.last_index = -1;
  253. return PARSE_OK;
  254. }
  255. }
  256. default:
  257. LOG(ERROR) << "Invalid first character=" << (int)fc;
  258. return PARSE_ERROR_ABSOLUTELY_WRONG;
  259. }
  260. return PARSE_ERROR_ABSOLUTELY_WRONG;
  261. }
  262. class RedisStringPrinter {
  263. public:
  264. RedisStringPrinter(const char* str, size_t length)
  265. : _str(str, length) {}
  266. void Print(std::ostream& os) const;
  267. private:
  268. butil::StringPiece _str;
  269. };
  270. static std::ostream&
  271. operator<<(std::ostream& os, const RedisStringPrinter& printer) {
  272. printer.Print(os);
  273. return os;
  274. }
  275. void RedisStringPrinter::Print(std::ostream& os) const {
  276. size_t flush_start = 0;
  277. for (size_t i = 0; i < _str.size(); ++i) {
  278. const char c = _str[i];
  279. if (c <= 0) { // unprintable chars
  280. if (i != flush_start) {
  281. os << butil::StringPiece(_str.data() + flush_start, i - flush_start);
  282. }
  283. char buf[8] = "\\u0000";
  284. uint8_t d1 = ((uint8_t)c) & 0xF;
  285. uint8_t d2 = ((uint8_t)c) >> 4;
  286. buf[4] = (d1 < 10 ? d1 + '0' : (d1 - 10) + 'A');
  287. buf[5] = (d2 < 10 ? d2 + '0' : (d2 - 10) + 'A');
  288. os << butil::StringPiece(buf, 6);
  289. flush_start = i + 1;
  290. } else if (c == '"' || c == '\\') { // need to escape
  291. if (i != flush_start) {
  292. os << butil::StringPiece(_str.data() + flush_start, i - flush_start);
  293. }
  294. os << '\\' << c;
  295. flush_start = i + 1;
  296. }
  297. }
  298. if (flush_start != _str.size()) {
  299. os << butil::StringPiece(_str.data() + flush_start, _str.size() - flush_start);
  300. }
  301. }
  302. // Mimic how official redis-cli prints.
  303. void RedisReply::Print(std::ostream& os) const {
  304. switch (_type) {
  305. case REDIS_REPLY_STRING:
  306. os << '"';
  307. if (_length < (int)sizeof(_data.short_str)) {
  308. os << RedisStringPrinter(_data.short_str, _length);
  309. } else {
  310. os << RedisStringPrinter(_data.long_str, _length);
  311. }
  312. os << '"';
  313. break;
  314. case REDIS_REPLY_ARRAY:
  315. os << '[';
  316. for (int i = 0; i < _length; ++i) {
  317. if (i != 0) {
  318. os << ", ";
  319. }
  320. _data.array.replies[i].Print(os);
  321. }
  322. os << ']';
  323. break;
  324. case REDIS_REPLY_INTEGER:
  325. os << "(integer) " << _data.integer;
  326. break;
  327. case REDIS_REPLY_NIL:
  328. os << "(nil)";
  329. break;
  330. case REDIS_REPLY_ERROR:
  331. os << "(error) ";
  332. // fall through
  333. case REDIS_REPLY_STATUS:
  334. if (_length < (int)sizeof(_data.short_str)) {
  335. os << RedisStringPrinter(_data.short_str, _length);
  336. } else {
  337. os << RedisStringPrinter(_data.long_str, _length);
  338. }
  339. break;
  340. default:
  341. os << "UnknownType=" << _type;
  342. break;
  343. }
  344. }
  345. void RedisReply::CopyFromDifferentArena(const RedisReply& other) {
  346. _type = other._type;
  347. _length = other._length;
  348. switch (_type) {
  349. case REDIS_REPLY_ARRAY: {
  350. RedisReply* subs = (RedisReply*)_arena->allocate(sizeof(RedisReply) * _length);
  351. if (subs == NULL) {
  352. LOG(FATAL) << "Fail to allocate RedisReply[" << _length << "]";
  353. return;
  354. }
  355. for (int i = 0; i < _length; ++i) {
  356. new (&subs[i]) RedisReply(_arena);
  357. }
  358. _data.array.last_index = other._data.array.last_index;
  359. if (_data.array.last_index > 0) {
  360. // incomplete state
  361. for (int i = 0; i < _data.array.last_index; ++i) {
  362. subs[i].CopyFromDifferentArena(other._data.array.replies[i]);
  363. }
  364. } else {
  365. for (int i = 0; i < _length; ++i) {
  366. subs[i].CopyFromDifferentArena(other._data.array.replies[i]);
  367. }
  368. }
  369. _data.array.replies = subs;
  370. }
  371. break;
  372. case REDIS_REPLY_INTEGER:
  373. _data.integer = other._data.integer;
  374. break;
  375. case REDIS_REPLY_NIL:
  376. break;
  377. case REDIS_REPLY_STRING:
  378. // fall through
  379. case REDIS_REPLY_ERROR:
  380. // fall through
  381. case REDIS_REPLY_STATUS:
  382. if (_length < (int)sizeof(_data.short_str)) {
  383. memcpy(_data.short_str, other._data.short_str, _length + 1);
  384. } else {
  385. char* d = (char*)_arena->allocate((_length/8 + 1)*8);
  386. if (d == NULL) {
  387. LOG(FATAL) << "Fail to allocate string[" << _length << "]";
  388. return;
  389. }
  390. memcpy(d, other._data.long_str, _length + 1);
  391. _data.long_str = d;
  392. }
  393. break;
  394. }
  395. }
  396. void RedisReply::SetArray(int size) {
  397. if (_type != REDIS_REPLY_NIL) {
  398. Reset();
  399. }
  400. _type = REDIS_REPLY_ARRAY;
  401. if (size < 0) {
  402. LOG(ERROR) << "negative size=" << size << " when calling SetArray";
  403. return;
  404. } else if (size == 0) {
  405. _length = 0;
  406. return;
  407. }
  408. RedisReply* subs = (RedisReply*)_arena->allocate(sizeof(RedisReply) * size);
  409. if (!subs) {
  410. LOG(FATAL) << "Fail to allocate RedisReply[" << size << "]";
  411. return;
  412. }
  413. for (int i = 0; i < size; ++i) {
  414. new (&subs[i]) RedisReply(_arena);
  415. }
  416. _length = size;
  417. _data.array.replies = subs;
  418. }
  419. void RedisReply::SetStringImpl(const butil::StringPiece& str, RedisReplyType type) {
  420. if (_type != REDIS_REPLY_NIL) {
  421. Reset();
  422. }
  423. const size_t size = str.size();
  424. if (size < sizeof(_data.short_str)) {
  425. memcpy(_data.short_str, str.data(), size);
  426. _data.short_str[size] = '\0';
  427. } else {
  428. char* d = (char*)_arena->allocate((size/8 + 1) * 8);
  429. if (!d) {
  430. LOG(FATAL) << "Fail to allocate string[" << size << "]";
  431. return;
  432. }
  433. memcpy(d, str.data(), size);
  434. d[size] = '\0';
  435. _data.long_str = d;
  436. }
  437. _type = type;
  438. _length = size;
  439. }
  440. void RedisReply::FormatStringImpl(const char* fmt, va_list args, RedisReplyType type) {
  441. va_list copied_args;
  442. va_copy(copied_args, args);
  443. char buf[64];
  444. int ret = vsnprintf(buf, sizeof(buf), fmt, copied_args);
  445. va_end(copied_args);
  446. if (ret < 0) {
  447. LOG(FATAL) << "Fail to vsnprintf into buf=" << (void*)buf << " size=" << sizeof(buf);
  448. return;
  449. } else if (ret < (int)sizeof(buf)) {
  450. return SetStringImpl(buf, type);
  451. } else {
  452. std::string str;
  453. str.reserve(ret + 1);
  454. butil::string_vappendf(&str, fmt, args);
  455. return SetStringImpl(str, type);
  456. }
  457. }
  458. } // namespace brpc