You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hiredis.c 34KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. /*
  2. * Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com>
  3. * Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>
  4. *
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * * Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * * Neither the name of Redis nor the names of its contributors may be used
  16. * to endorse or promote products derived from this software without
  17. * specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  23. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  24. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  25. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  26. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  27. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  29. * POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #include "fmacros.h"
  32. #include <string.h>
  33. #include <stdlib.h>
  34. #include <unistd.h>
  35. #include <assert.h>
  36. #include <errno.h>
  37. #include <ctype.h>
  38. #include "hiredis.h"
  39. #include "net.h"
  40. #include "sds.h"
  41. static redisReply *createReplyObject(int type);
  42. static void *createStringObject(const redisReadTask *task, char *str, size_t len);
  43. static void *createArrayObject(const redisReadTask *task, int elements);
  44. static void *createIntegerObject(const redisReadTask *task, long long value);
  45. static void *createNilObject(const redisReadTask *task);
  46. /* Default set of functions to build the reply. Keep in mind that such a
  47. * function returning NULL is interpreted as OOM. */
  48. static redisReplyObjectFunctions defaultFunctions = {
  49. createStringObject,
  50. createArrayObject,
  51. createIntegerObject,
  52. createNilObject,
  53. freeReplyObject
  54. };
  55. /* Create a reply object */
  56. static redisReply *createReplyObject(int type) {
  57. redisReply *r = calloc(1,sizeof(*r));
  58. if (r == NULL)
  59. return NULL;
  60. r->type = type;
  61. return r;
  62. }
  63. /* Free a reply object */
  64. void freeReplyObject(void *reply) {
  65. redisReply *r = reply;
  66. size_t j;
  67. switch(r->type) {
  68. case REDIS_REPLY_INTEGER:
  69. break; /* Nothing to free */
  70. case REDIS_REPLY_ARRAY:
  71. if (r->element != NULL) {
  72. for (j = 0; j < r->elements; j++)
  73. if (r->element[j] != NULL)
  74. freeReplyObject(r->element[j]);
  75. free(r->element);
  76. }
  77. break;
  78. case REDIS_REPLY_ERROR:
  79. case REDIS_REPLY_STATUS:
  80. case REDIS_REPLY_STRING:
  81. if (r->str != NULL)
  82. free(r->str);
  83. break;
  84. }
  85. free(r);
  86. }
  87. static void *createStringObject(const redisReadTask *task, char *str, size_t len) {
  88. redisReply *r, *parent;
  89. char *buf;
  90. r = createReplyObject(task->type);
  91. if (r == NULL)
  92. return NULL;
  93. buf = malloc(len+1);
  94. if (buf == NULL) {
  95. freeReplyObject(r);
  96. return NULL;
  97. }
  98. assert(task->type == REDIS_REPLY_ERROR ||
  99. task->type == REDIS_REPLY_STATUS ||
  100. task->type == REDIS_REPLY_STRING);
  101. /* Copy string value */
  102. memcpy(buf,str,len);
  103. buf[len] = '\0';
  104. r->str = buf;
  105. r->len = len;
  106. if (task->parent) {
  107. parent = task->parent->obj;
  108. assert(parent->type == REDIS_REPLY_ARRAY);
  109. parent->element[task->idx] = r;
  110. }
  111. return r;
  112. }
  113. static void *createArrayObject(const redisReadTask *task, int elements) {
  114. redisReply *r, *parent;
  115. r = createReplyObject(REDIS_REPLY_ARRAY);
  116. if (r == NULL)
  117. return NULL;
  118. if (elements > 0) {
  119. r->element = calloc(elements,sizeof(redisReply*));
  120. if (r->element == NULL) {
  121. freeReplyObject(r);
  122. return NULL;
  123. }
  124. }
  125. r->elements = elements;
  126. if (task->parent) {
  127. parent = task->parent->obj;
  128. assert(parent->type == REDIS_REPLY_ARRAY);
  129. parent->element[task->idx] = r;
  130. }
  131. return r;
  132. }
  133. static void *createIntegerObject(const redisReadTask *task, long long value) {
  134. redisReply *r, *parent;
  135. r = createReplyObject(REDIS_REPLY_INTEGER);
  136. if (r == NULL)
  137. return NULL;
  138. r->integer = value;
  139. if (task->parent) {
  140. parent = task->parent->obj;
  141. assert(parent->type == REDIS_REPLY_ARRAY);
  142. parent->element[task->idx] = r;
  143. }
  144. return r;
  145. }
  146. static void *createNilObject(const redisReadTask *task) {
  147. redisReply *r, *parent;
  148. r = createReplyObject(REDIS_REPLY_NIL);
  149. if (r == NULL)
  150. return NULL;
  151. if (task->parent) {
  152. parent = task->parent->obj;
  153. assert(parent->type == REDIS_REPLY_ARRAY);
  154. parent->element[task->idx] = r;
  155. }
  156. return r;
  157. }
  158. static void __redisReaderSetError(redisReader *r, int type, const char *str) {
  159. size_t len;
  160. if (r->reply != NULL && r->fn && r->fn->freeObject) {
  161. r->fn->freeObject(r->reply);
  162. r->reply = NULL;
  163. }
  164. /* Clear input buffer on errors. */
  165. if (r->buf != NULL) {
  166. sdsfree(r->buf);
  167. r->buf = NULL;
  168. r->pos = r->len = 0;
  169. }
  170. /* Reset task stack. */
  171. r->ridx = -1;
  172. /* Set error. */
  173. r->err = type;
  174. len = strlen(str);
  175. len = len < (sizeof(r->errstr)-1) ? len : (sizeof(r->errstr)-1);
  176. memcpy(r->errstr,str,len);
  177. r->errstr[len] = '\0';
  178. }
  179. static size_t chrtos(char *buf, size_t size, char byte) {
  180. size_t len = 0;
  181. switch(byte) {
  182. case '\\':
  183. case '"':
  184. len = snprintf(buf,size,"\"\\%c\"",byte);
  185. break;
  186. case '\n': len = snprintf(buf,size,"\"\\n\""); break;
  187. case '\r': len = snprintf(buf,size,"\"\\r\""); break;
  188. case '\t': len = snprintf(buf,size,"\"\\t\""); break;
  189. case '\a': len = snprintf(buf,size,"\"\\a\""); break;
  190. case '\b': len = snprintf(buf,size,"\"\\b\""); break;
  191. default:
  192. if (isprint(byte))
  193. len = snprintf(buf,size,"\"%c\"",byte);
  194. else
  195. len = snprintf(buf,size,"\"\\x%02x\"",(unsigned char)byte);
  196. break;
  197. }
  198. return len;
  199. }
  200. static void __redisReaderSetErrorProtocolByte(redisReader *r, char byte) {
  201. char cbuf[8], sbuf[128];
  202. chrtos(cbuf,sizeof(cbuf),byte);
  203. snprintf(sbuf,sizeof(sbuf),
  204. "Protocol error, got %s as reply type byte", cbuf);
  205. __redisReaderSetError(r,REDIS_ERR_PROTOCOL,sbuf);
  206. }
  207. static void __redisReaderSetErrorOOM(redisReader *r) {
  208. __redisReaderSetError(r,REDIS_ERR_OOM,"Out of memory");
  209. }
  210. static char *readBytes(redisReader *r, unsigned int bytes) {
  211. char *p;
  212. if (r->len-r->pos >= bytes) {
  213. p = r->buf+r->pos;
  214. r->pos += bytes;
  215. return p;
  216. }
  217. return NULL;
  218. }
  219. /* Find pointer to \r\n. */
  220. static char *seekNewline(char *s, size_t len) {
  221. int pos = 0;
  222. int _len = len-1;
  223. /* Position should be < len-1 because the character at "pos" should be
  224. * followed by a \n. Note that strchr cannot be used because it doesn't
  225. * allow to search a limited length and the buffer that is being searched
  226. * might not have a trailing NULL character. */
  227. while (pos < _len) {
  228. while(pos < _len && s[pos] != '\r') pos++;
  229. if (s[pos] != '\r') {
  230. /* Not found. */
  231. return NULL;
  232. } else {
  233. if (s[pos+1] == '\n') {
  234. /* Found. */
  235. return s+pos;
  236. } else {
  237. /* Continue searching. */
  238. pos++;
  239. }
  240. }
  241. }
  242. return NULL;
  243. }
  244. /* Read a long long value starting at *s, under the assumption that it will be
  245. * terminated by \r\n. Ambiguously returns -1 for unexpected input. */
  246. static long long readLongLong(char *s) {
  247. long long v = 0;
  248. int dec, mult = 1;
  249. char c;
  250. if (*s == '-') {
  251. mult = -1;
  252. s++;
  253. } else if (*s == '+') {
  254. mult = 1;
  255. s++;
  256. }
  257. while ((c = *(s++)) != '\r') {
  258. dec = c - '0';
  259. if (dec >= 0 && dec < 10) {
  260. v *= 10;
  261. v += dec;
  262. } else {
  263. /* Should not happen... */
  264. return -1;
  265. }
  266. }
  267. return mult*v;
  268. }
  269. static char *readLine(redisReader *r, int *_len) {
  270. char *p, *s;
  271. int len;
  272. p = r->buf+r->pos;
  273. s = seekNewline(p,(r->len-r->pos));
  274. if (s != NULL) {
  275. len = s-(r->buf+r->pos);
  276. r->pos += len+2; /* skip \r\n */
  277. if (_len) *_len = len;
  278. return p;
  279. }
  280. return NULL;
  281. }
  282. static void moveToNextTask(redisReader *r) {
  283. redisReadTask *cur, *prv;
  284. while (r->ridx >= 0) {
  285. /* Return a.s.a.p. when the stack is now empty. */
  286. if (r->ridx == 0) {
  287. r->ridx--;
  288. return;
  289. }
  290. cur = &(r->rstack[r->ridx]);
  291. prv = &(r->rstack[r->ridx-1]);
  292. assert(prv->type == REDIS_REPLY_ARRAY);
  293. if (cur->idx == prv->elements-1) {
  294. r->ridx--;
  295. } else {
  296. /* Reset the type because the next item can be anything */
  297. assert(cur->idx < prv->elements);
  298. cur->type = -1;
  299. cur->elements = -1;
  300. cur->idx++;
  301. return;
  302. }
  303. }
  304. }
  305. static int processLineItem(redisReader *r) {
  306. redisReadTask *cur = &(r->rstack[r->ridx]);
  307. void *obj;
  308. char *p;
  309. int len;
  310. if ((p = readLine(r,&len)) != NULL) {
  311. if (cur->type == REDIS_REPLY_INTEGER) {
  312. if (r->fn && r->fn->createInteger)
  313. obj = r->fn->createInteger(cur,readLongLong(p));
  314. else
  315. obj = (void*)REDIS_REPLY_INTEGER;
  316. } else {
  317. /* Type will be error or status. */
  318. if (r->fn && r->fn->createString)
  319. obj = r->fn->createString(cur,p,len);
  320. else
  321. obj = (void*)(size_t)(cur->type);
  322. }
  323. if (obj == NULL) {
  324. __redisReaderSetErrorOOM(r);
  325. return REDIS_ERR;
  326. }
  327. /* Set reply if this is the root object. */
  328. if (r->ridx == 0) r->reply = obj;
  329. moveToNextTask(r);
  330. return REDIS_OK;
  331. }
  332. return REDIS_ERR;
  333. }
  334. static int processBulkItem(redisReader *r) {
  335. redisReadTask *cur = &(r->rstack[r->ridx]);
  336. void *obj = NULL;
  337. char *p, *s;
  338. long len;
  339. unsigned long bytelen;
  340. int success = 0;
  341. p = r->buf+r->pos;
  342. s = seekNewline(p,r->len-r->pos);
  343. if (s != NULL) {
  344. p = r->buf+r->pos;
  345. bytelen = s-(r->buf+r->pos)+2; /* include \r\n */
  346. len = readLongLong(p);
  347. if (len < 0) {
  348. /* The nil object can always be created. */
  349. if (r->fn && r->fn->createNil)
  350. obj = r->fn->createNil(cur);
  351. else
  352. obj = (void*)REDIS_REPLY_NIL;
  353. success = 1;
  354. } else {
  355. /* Only continue when the buffer contains the entire bulk item. */
  356. bytelen += len+2; /* include \r\n */
  357. if (r->pos+bytelen <= r->len) {
  358. if (r->fn && r->fn->createString)
  359. obj = r->fn->createString(cur,s+2,len);
  360. else
  361. obj = (void*)REDIS_REPLY_STRING;
  362. success = 1;
  363. }
  364. }
  365. /* Proceed when obj was created. */
  366. if (success) {
  367. if (obj == NULL) {
  368. __redisReaderSetErrorOOM(r);
  369. return REDIS_ERR;
  370. }
  371. r->pos += bytelen;
  372. /* Set reply if this is the root object. */
  373. if (r->ridx == 0) r->reply = obj;
  374. moveToNextTask(r);
  375. return REDIS_OK;
  376. }
  377. }
  378. return REDIS_ERR;
  379. }
  380. static int processMultiBulkItem(redisReader *r) {
  381. redisReadTask *cur = &(r->rstack[r->ridx]);
  382. void *obj;
  383. char *p;
  384. long elements;
  385. int root = 0;
  386. /* Set error for nested multi bulks with depth > 1 */
  387. if (r->ridx == 2) {
  388. __redisReaderSetError(r,REDIS_ERR_PROTOCOL,
  389. "No support for nested multi bulk replies with depth > 1");
  390. return REDIS_ERR;
  391. }
  392. if ((p = readLine(r,NULL)) != NULL) {
  393. elements = readLongLong(p);
  394. root = (r->ridx == 0);
  395. if (elements == -1) {
  396. if (r->fn && r->fn->createNil)
  397. obj = r->fn->createNil(cur);
  398. else
  399. obj = (void*)REDIS_REPLY_NIL;
  400. if (obj == NULL) {
  401. __redisReaderSetErrorOOM(r);
  402. return REDIS_ERR;
  403. }
  404. moveToNextTask(r);
  405. } else {
  406. if (r->fn && r->fn->createArray)
  407. obj = r->fn->createArray(cur,elements);
  408. else
  409. obj = (void*)REDIS_REPLY_ARRAY;
  410. if (obj == NULL) {
  411. __redisReaderSetErrorOOM(r);
  412. return REDIS_ERR;
  413. }
  414. /* Modify task stack when there are more than 0 elements. */
  415. if (elements > 0) {
  416. cur->elements = elements;
  417. cur->obj = obj;
  418. r->ridx++;
  419. r->rstack[r->ridx].type = -1;
  420. r->rstack[r->ridx].elements = -1;
  421. r->rstack[r->ridx].idx = 0;
  422. r->rstack[r->ridx].obj = NULL;
  423. r->rstack[r->ridx].parent = cur;
  424. r->rstack[r->ridx].privdata = r->privdata;
  425. } else {
  426. moveToNextTask(r);
  427. }
  428. }
  429. /* Set reply if this is the root object. */
  430. if (root) r->reply = obj;
  431. return REDIS_OK;
  432. }
  433. return REDIS_ERR;
  434. }
  435. static int processItem(redisReader *r) {
  436. redisReadTask *cur = &(r->rstack[r->ridx]);
  437. char *p;
  438. /* check if we need to read type */
  439. if (cur->type < 0) {
  440. if ((p = readBytes(r,1)) != NULL) {
  441. switch (p[0]) {
  442. case '-':
  443. cur->type = REDIS_REPLY_ERROR;
  444. break;
  445. case '+':
  446. cur->type = REDIS_REPLY_STATUS;
  447. break;
  448. case ':':
  449. cur->type = REDIS_REPLY_INTEGER;
  450. break;
  451. case '$':
  452. cur->type = REDIS_REPLY_STRING;
  453. break;
  454. case '*':
  455. cur->type = REDIS_REPLY_ARRAY;
  456. break;
  457. default:
  458. __redisReaderSetErrorProtocolByte(r,*p);
  459. return REDIS_ERR;
  460. }
  461. } else {
  462. /* could not consume 1 byte */
  463. return REDIS_ERR;
  464. }
  465. }
  466. /* process typed item */
  467. switch(cur->type) {
  468. case REDIS_REPLY_ERROR:
  469. case REDIS_REPLY_STATUS:
  470. case REDIS_REPLY_INTEGER:
  471. return processLineItem(r);
  472. case REDIS_REPLY_STRING:
  473. return processBulkItem(r);
  474. case REDIS_REPLY_ARRAY:
  475. return processMultiBulkItem(r);
  476. default:
  477. assert(NULL);
  478. return REDIS_ERR; /* Avoid warning. */
  479. }
  480. }
  481. redisReader *redisReaderCreate(void) {
  482. redisReader *r;
  483. r = calloc(sizeof(redisReader),1);
  484. if (r == NULL)
  485. return NULL;
  486. r->err = 0;
  487. r->errstr[0] = '\0';
  488. r->fn = &defaultFunctions;
  489. r->buf = sdsempty();
  490. if (r->buf == NULL) {
  491. free(r);
  492. return NULL;
  493. }
  494. r->ridx = -1;
  495. return r;
  496. }
  497. void redisReaderFree(redisReader *r) {
  498. if (r->reply != NULL && r->fn && r->fn->freeObject)
  499. r->fn->freeObject(r->reply);
  500. if (r->buf != NULL)
  501. sdsfree(r->buf);
  502. free(r);
  503. }
  504. int redisReaderFeed(redisReader *r, const char *buf, size_t len) {
  505. sds newbuf;
  506. /* Return early when this reader is in an erroneous state. */
  507. if (r->err)
  508. return REDIS_ERR;
  509. /* Copy the provided buffer. */
  510. if (buf != NULL && len >= 1) {
  511. /* Destroy internal buffer when it is empty and is quite large. */
  512. if (r->len == 0 && sdsavail(r->buf) > 16*1024) {
  513. sdsfree(r->buf);
  514. r->buf = sdsempty();
  515. r->pos = 0;
  516. /* r->buf should not be NULL since we just free'd a larger one. */
  517. assert(r->buf != NULL);
  518. }
  519. newbuf = sdscatlen(r->buf,buf,len);
  520. if (newbuf == NULL) {
  521. __redisReaderSetErrorOOM(r);
  522. return REDIS_ERR;
  523. }
  524. r->buf = newbuf;
  525. r->len = sdslen(r->buf);
  526. }
  527. return REDIS_OK;
  528. }
  529. int redisReaderGetReply(redisReader *r, void **reply) {
  530. /* Default target pointer to NULL. */
  531. if (reply != NULL)
  532. *reply = NULL;
  533. /* Return early when this reader is in an erroneous state. */
  534. if (r->err)
  535. return REDIS_ERR;
  536. /* When the buffer is empty, there will never be a reply. */
  537. if (r->len == 0)
  538. return REDIS_OK;
  539. /* Set first item to process when the stack is empty. */
  540. if (r->ridx == -1) {
  541. r->rstack[0].type = -1;
  542. r->rstack[0].elements = -1;
  543. r->rstack[0].idx = -1;
  544. r->rstack[0].obj = NULL;
  545. r->rstack[0].parent = NULL;
  546. r->rstack[0].privdata = r->privdata;
  547. r->ridx = 0;
  548. }
  549. /* Process items in reply. */
  550. while (r->ridx >= 0)
  551. if (processItem(r) != REDIS_OK)
  552. break;
  553. /* Return ASAP when an error occurred. */
  554. if (r->err)
  555. return REDIS_ERR;
  556. /* Discard part of the buffer when we've consumed at least 1k, to avoid
  557. * doing unnecessary calls to memmove() in sds.c. */
  558. if (r->pos >= 1024) {
  559. r->buf = sdsrange(r->buf,r->pos,-1);
  560. r->pos = 0;
  561. r->len = sdslen(r->buf);
  562. }
  563. /* Emit a reply when there is one. */
  564. if (r->ridx == -1) {
  565. if (reply != NULL)
  566. *reply = r->reply;
  567. r->reply = NULL;
  568. }
  569. return REDIS_OK;
  570. }
  571. /* Calculate the number of bytes needed to represent an integer as string. */
  572. static int intlen(int i) {
  573. int len = 0;
  574. if (i < 0) {
  575. len++;
  576. i = -i;
  577. }
  578. do {
  579. len++;
  580. i /= 10;
  581. } while(i);
  582. return len;
  583. }
  584. /* Helper that calculates the bulk length given a certain string length. */
  585. static size_t bulklen(size_t len) {
  586. return 1+intlen(len)+2+len+2;
  587. }
  588. int redisvFormatCommand(char **target, const char *format, va_list ap) {
  589. const char *c = format;
  590. char *cmd = NULL; /* final command */
  591. int pos; /* position in final command */
  592. sds curarg, newarg; /* current argument */
  593. int touched = 0; /* was the current argument touched? */
  594. char **curargv = NULL, **newargv = NULL;
  595. int argc = 0;
  596. int totlen = 0;
  597. int j;
  598. /* Abort if there is not target to set */
  599. if (target == NULL)
  600. return -1;
  601. /* Build the command string accordingly to protocol */
  602. curarg = sdsempty();
  603. if (curarg == NULL)
  604. return -1;
  605. while(*c != '\0') {
  606. if (*c != '%' || c[1] == '\0') {
  607. if (*c == ' ') {
  608. if (touched) {
  609. newargv = realloc(curargv,sizeof(char*)*(argc+1));
  610. if (newargv == NULL) goto err;
  611. curargv = newargv;
  612. curargv[argc++] = curarg;
  613. totlen += bulklen(sdslen(curarg));
  614. /* curarg is put in argv so it can be overwritten. */
  615. curarg = sdsempty();
  616. if (curarg == NULL) goto err;
  617. touched = 0;
  618. }
  619. } else {
  620. newarg = sdscatlen(curarg,c,1);
  621. if (newarg == NULL) goto err;
  622. curarg = newarg;
  623. touched = 1;
  624. }
  625. } else {
  626. char *arg;
  627. size_t size;
  628. /* Set newarg so it can be checked even if it is not touched. */
  629. newarg = curarg;
  630. switch(c[1]) {
  631. case 's':
  632. arg = va_arg(ap,char*);
  633. size = strlen(arg);
  634. if (size > 0)
  635. newarg = sdscatlen(curarg,arg,size);
  636. break;
  637. case 'b':
  638. arg = va_arg(ap,char*);
  639. size = va_arg(ap,size_t);
  640. if (size > 0)
  641. newarg = sdscatlen(curarg,arg,size);
  642. break;
  643. case '%':
  644. newarg = sdscat(curarg,"%");
  645. break;
  646. default:
  647. /* Try to detect printf format */
  648. {
  649. char _format[16];
  650. const char *_p = c+1;
  651. size_t _l = 0;
  652. va_list _cpy;
  653. /* Flags */
  654. if (*_p != '\0' && *_p == '#') _p++;
  655. if (*_p != '\0' && *_p == '0') _p++;
  656. if (*_p != '\0' && *_p == '-') _p++;
  657. if (*_p != '\0' && *_p == ' ') _p++;
  658. if (*_p != '\0' && *_p == '+') _p++;
  659. /* Field width */
  660. while (*_p != '\0' && isdigit(*_p)) _p++;
  661. /* Precision */
  662. if (*_p == '.') {
  663. _p++;
  664. while (*_p != '\0' && isdigit(*_p)) _p++;
  665. }
  666. /* Modifiers */
  667. if (*_p != '\0') {
  668. if (*_p == 'h' || *_p == 'l') {
  669. /* Allow a single repetition for these modifiers */
  670. if (_p[0] == _p[1]) _p++;
  671. _p++;
  672. }
  673. }
  674. /* Conversion specifier */
  675. if (*_p != '\0' && strchr("diouxXeEfFgGaA",*_p) != NULL) {
  676. _l = (_p+1)-c;
  677. if (_l < sizeof(_format)-2) {
  678. memcpy(_format,c,_l);
  679. _format[_l] = '\0';
  680. va_copy(_cpy,ap);
  681. newarg = sdscatvprintf(curarg,_format,_cpy);
  682. va_end(_cpy);
  683. /* Update current position (note: outer blocks
  684. * increment c twice so compensate here) */
  685. c = _p-1;
  686. }
  687. }
  688. /* Consume and discard vararg */
  689. (void)va_arg(ap,int);
  690. }
  691. }
  692. if (newarg == NULL) goto err;
  693. curarg = newarg;
  694. touched = 1;
  695. c++;
  696. }
  697. c++;
  698. }
  699. /* Add the last argument if needed */
  700. if (touched) {
  701. newargv = realloc(curargv,sizeof(char*)*(argc+1));
  702. if (newargv == NULL) goto err;
  703. curargv = newargv;
  704. curargv[argc++] = curarg;
  705. totlen += bulklen(sdslen(curarg));
  706. } else {
  707. sdsfree(curarg);
  708. }
  709. /* Clear curarg because it was put in curargv or was free'd. */
  710. curarg = NULL;
  711. /* Add bytes needed to hold multi bulk count */
  712. totlen += 1+intlen(argc)+2;
  713. /* Build the command at protocol level */
  714. cmd = malloc(totlen+1);
  715. if (cmd == NULL) goto err;
  716. pos = sprintf(cmd,"*%d\r\n",argc);
  717. for (j = 0; j < argc; j++) {
  718. pos += sprintf(cmd+pos,"$%zu\r\n",sdslen(curargv[j]));
  719. memcpy(cmd+pos,curargv[j],sdslen(curargv[j]));
  720. pos += sdslen(curargv[j]);
  721. sdsfree(curargv[j]);
  722. cmd[pos++] = '\r';
  723. cmd[pos++] = '\n';
  724. }
  725. assert(pos == totlen);
  726. cmd[pos] = '\0';
  727. free(curargv);
  728. *target = cmd;
  729. return totlen;
  730. err:
  731. while(argc--)
  732. sdsfree(curargv[argc]);
  733. free(curargv);
  734. if (curarg != NULL)
  735. sdsfree(curarg);
  736. /* No need to check cmd since it is the last statement that can fail,
  737. * but do it anyway to be as defensive as possible. */
  738. if (cmd != NULL)
  739. free(cmd);
  740. return -1;
  741. }
  742. /* Format a command according to the Redis protocol. This function
  743. * takes a format similar to printf:
  744. *
  745. * %s represents a C null terminated string you want to interpolate
  746. * %b represents a binary safe string
  747. *
  748. * When using %b you need to provide both the pointer to the string
  749. * and the length in bytes. Examples:
  750. *
  751. * len = redisFormatCommand(target, "GET %s", mykey);
  752. * len = redisFormatCommand(target, "SET %s %b", mykey, myval, myvallen);
  753. */
  754. int redisFormatCommand(char **target, const char *format, ...) {
  755. va_list ap;
  756. int len;
  757. va_start(ap,format);
  758. len = redisvFormatCommand(target,format,ap);
  759. va_end(ap);
  760. return len;
  761. }
  762. /* Format a command according to the Redis protocol. This function takes the
  763. * number of arguments, an array with arguments and an array with their
  764. * lengths. If the latter is set to NULL, strlen will be used to compute the
  765. * argument lengths.
  766. */
  767. int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen) {
  768. char *cmd = NULL; /* final command */
  769. int pos; /* position in final command */
  770. size_t len;
  771. int totlen, j;
  772. /* Calculate number of bytes needed for the command */
  773. totlen = 1+intlen(argc)+2;
  774. for (j = 0; j < argc; j++) {
  775. len = argvlen ? argvlen[j] : strlen(argv[j]);
  776. totlen += bulklen(len);
  777. }
  778. /* Build the command at protocol level */
  779. cmd = malloc(totlen+1);
  780. if (cmd == NULL)
  781. return -1;
  782. pos = sprintf(cmd,"*%d\r\n",argc);
  783. for (j = 0; j < argc; j++) {
  784. len = argvlen ? argvlen[j] : strlen(argv[j]);
  785. pos += sprintf(cmd+pos,"$%zu\r\n",len);
  786. memcpy(cmd+pos,argv[j],len);
  787. pos += len;
  788. cmd[pos++] = '\r';
  789. cmd[pos++] = '\n';
  790. }
  791. assert(pos == totlen);
  792. cmd[pos] = '\0';
  793. *target = cmd;
  794. return totlen;
  795. }
  796. void __redisSetError(redisContext *c, int type, const char *str) {
  797. size_t len;
  798. c->err = type;
  799. if (str != NULL) {
  800. len = strlen(str);
  801. len = len < (sizeof(c->errstr)-1) ? len : (sizeof(c->errstr)-1);
  802. memcpy(c->errstr,str,len);
  803. c->errstr[len] = '\0';
  804. } else {
  805. /* Only REDIS_ERR_IO may lack a description! */
  806. assert(type == REDIS_ERR_IO);
  807. strerror_r(errno,c->errstr,sizeof(c->errstr));
  808. }
  809. }
  810. static redisContext *redisContextInit(void) {
  811. redisContext *c;
  812. c = calloc(1,sizeof(redisContext));
  813. if (c == NULL)
  814. return NULL;
  815. c->err = 0;
  816. c->errstr[0] = '\0';
  817. c->obuf = sdsempty();
  818. c->reader = redisReaderCreate();
  819. return c;
  820. }
  821. void redisFree(redisContext *c) {
  822. if (c->fd > 0)
  823. close(c->fd);
  824. if (c->obuf != NULL)
  825. sdsfree(c->obuf);
  826. if (c->reader != NULL)
  827. redisReaderFree(c->reader);
  828. free(c);
  829. }
  830. /* Connect to a Redis instance. On error the field error in the returned
  831. * context will be set to the return value of the error function.
  832. * When no set of reply functions is given, the default set will be used. */
  833. redisContext *redisConnect(const char *ip, int port) {
  834. redisContext *c = redisContextInit();
  835. c->flags |= REDIS_BLOCK;
  836. redisContextConnectTcp(c,ip,port,NULL);
  837. return c;
  838. }
  839. redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv) {
  840. redisContext *c = redisContextInit();
  841. c->flags |= REDIS_BLOCK;
  842. redisContextConnectTcp(c,ip,port,&tv);
  843. return c;
  844. }
  845. redisContext *redisConnectNonBlock(const char *ip, int port) {
  846. redisContext *c = redisContextInit();
  847. c->flags &= ~REDIS_BLOCK;
  848. redisContextConnectTcp(c,ip,port,NULL);
  849. return c;
  850. }
  851. redisContext *redisConnectUnix(const char *path) {
  852. redisContext *c = redisContextInit();
  853. c->flags |= REDIS_BLOCK;
  854. redisContextConnectUnix(c,path,NULL);
  855. return c;
  856. }
  857. redisContext *redisConnectUnixWithTimeout(const char *path, struct timeval tv) {
  858. redisContext *c = redisContextInit();
  859. c->flags |= REDIS_BLOCK;
  860. redisContextConnectUnix(c,path,&tv);
  861. return c;
  862. }
  863. redisContext *redisConnectUnixNonBlock(const char *path) {
  864. redisContext *c = redisContextInit();
  865. c->flags &= ~REDIS_BLOCK;
  866. redisContextConnectUnix(c,path,NULL);
  867. return c;
  868. }
  869. /* Set read/write timeout on a blocking socket. */
  870. int redisSetTimeout(redisContext *c, struct timeval tv) {
  871. if (c->flags & REDIS_BLOCK)
  872. return redisContextSetTimeout(c,tv);
  873. return REDIS_ERR;
  874. }
  875. /* Use this function to handle a read event on the descriptor. It will try
  876. * and read some bytes from the socket and feed them to the reply parser.
  877. *
  878. * After this function is called, you may use redisContextReadReply to
  879. * see if there is a reply available. */
  880. int redisBufferRead(redisContext *c) {
  881. char buf[2048];
  882. int nread;
  883. /* Return early when the context has seen an error. */
  884. if (c->err)
  885. return REDIS_ERR;
  886. nread = read(c->fd,buf,sizeof(buf));
  887. if (nread == -1) {
  888. if (errno == EAGAIN && !(c->flags & REDIS_BLOCK)) {
  889. /* Try again later */
  890. } else {
  891. __redisSetError(c,REDIS_ERR_IO,NULL);
  892. return REDIS_ERR;
  893. }
  894. } else if (nread == 0) {
  895. __redisSetError(c,REDIS_ERR_EOF,"Server closed the connection");
  896. return REDIS_ERR;
  897. } else {
  898. if (redisReaderFeed(c->reader,buf,nread) != REDIS_OK) {
  899. __redisSetError(c,c->reader->err,c->reader->errstr);
  900. return REDIS_ERR;
  901. }
  902. }
  903. return REDIS_OK;
  904. }
  905. /* Write the output buffer to the socket.
  906. *
  907. * Returns REDIS_OK when the buffer is empty, or (a part of) the buffer was
  908. * succesfully written to the socket. When the buffer is empty after the
  909. * write operation, "wdone" is set to 1 (if given).
  910. *
  911. * Returns REDIS_ERR if an error occured trying to write and sets
  912. * c->error to hold the appropriate error string.
  913. */
  914. int redisBufferWrite(redisContext *c, int *done) {
  915. int nwritten;
  916. /* Return early when the context has seen an error. */
  917. if (c->err)
  918. return REDIS_ERR;
  919. if (sdslen(c->obuf) > 0) {
  920. nwritten = write(c->fd,c->obuf,sdslen(c->obuf));
  921. if (nwritten == -1) {
  922. if (errno == EAGAIN && !(c->flags & REDIS_BLOCK)) {
  923. /* Try again later */
  924. } else {
  925. __redisSetError(c,REDIS_ERR_IO,NULL);
  926. return REDIS_ERR;
  927. }
  928. } else if (nwritten > 0) {
  929. if (nwritten == (signed)sdslen(c->obuf)) {
  930. sdsfree(c->obuf);
  931. c->obuf = sdsempty();
  932. } else {
  933. c->obuf = sdsrange(c->obuf,nwritten,-1);
  934. }
  935. }
  936. }
  937. if (done != NULL) *done = (sdslen(c->obuf) == 0);
  938. return REDIS_OK;
  939. }
  940. /* Internal helper function to try and get a reply from the reader,
  941. * or set an error in the context otherwise. */
  942. int redisGetReplyFromReader(redisContext *c, void **reply) {
  943. if (redisReaderGetReply(c->reader,reply) == REDIS_ERR) {
  944. __redisSetError(c,c->reader->err,c->reader->errstr);
  945. return REDIS_ERR;
  946. }
  947. return REDIS_OK;
  948. }
  949. int redisGetReply(redisContext *c, void **reply) {
  950. int wdone = 0;
  951. void *aux = NULL;
  952. /* Try to read pending replies */
  953. if (redisGetReplyFromReader(c,&aux) == REDIS_ERR)
  954. return REDIS_ERR;
  955. /* For the blocking context, flush output buffer and read reply */
  956. if (aux == NULL && c->flags & REDIS_BLOCK) {
  957. /* Write until done */
  958. do {
  959. if (redisBufferWrite(c,&wdone) == REDIS_ERR)
  960. return REDIS_ERR;
  961. } while (!wdone);
  962. /* Read until there is a reply */
  963. do {
  964. if (redisBufferRead(c) == REDIS_ERR)
  965. return REDIS_ERR;
  966. if (redisGetReplyFromReader(c,&aux) == REDIS_ERR)
  967. return REDIS_ERR;
  968. } while (aux == NULL);
  969. }
  970. /* Set reply object */
  971. if (reply != NULL) *reply = aux;
  972. return REDIS_OK;
  973. }
  974. /* Helper function for the redisAppendCommand* family of functions.
  975. *
  976. * Write a formatted command to the output buffer. When this family
  977. * is used, you need to call redisGetReply yourself to retrieve
  978. * the reply (or replies in pub/sub).
  979. */
  980. int __redisAppendCommand(redisContext *c, char *cmd, size_t len) {
  981. sds newbuf;
  982. newbuf = sdscatlen(c->obuf,cmd,len);
  983. if (newbuf == NULL) {
  984. __redisSetError(c,REDIS_ERR_OOM,"Out of memory");
  985. return REDIS_ERR;
  986. }
  987. c->obuf = newbuf;
  988. return REDIS_OK;
  989. }
  990. int redisvAppendCommand(redisContext *c, const char *format, va_list ap) {
  991. char *cmd;
  992. int len;
  993. len = redisvFormatCommand(&cmd,format,ap);
  994. if (len == -1) {
  995. __redisSetError(c,REDIS_ERR_OOM,"Out of memory");
  996. return REDIS_ERR;
  997. }
  998. if (__redisAppendCommand(c,cmd,len) != REDIS_OK) {
  999. free(cmd);
  1000. return REDIS_ERR;
  1001. }
  1002. free(cmd);
  1003. return REDIS_OK;
  1004. }
  1005. int redisAppendCommand(redisContext *c, const char *format, ...) {
  1006. va_list ap;
  1007. int ret;
  1008. va_start(ap,format);
  1009. ret = redisvAppendCommand(c,format,ap);
  1010. va_end(ap);
  1011. return ret;
  1012. }
  1013. int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen) {
  1014. char *cmd;
  1015. int len;
  1016. len = redisFormatCommandArgv(&cmd,argc,argv,argvlen);
  1017. if (len == -1) {
  1018. __redisSetError(c,REDIS_ERR_OOM,"Out of memory");
  1019. return REDIS_ERR;
  1020. }
  1021. if (__redisAppendCommand(c,cmd,len) != REDIS_OK) {
  1022. free(cmd);
  1023. return REDIS_ERR;
  1024. }
  1025. free(cmd);
  1026. return REDIS_OK;
  1027. }
  1028. /* Helper function for the redisCommand* family of functions.
  1029. *
  1030. * Write a formatted command to the output buffer. If the given context is
  1031. * blocking, immediately read the reply into the "reply" pointer. When the
  1032. * context is non-blocking, the "reply" pointer will not be used and the
  1033. * command is simply appended to the write buffer.
  1034. *
  1035. * Returns the reply when a reply was succesfully retrieved. Returns NULL
  1036. * otherwise. When NULL is returned in a blocking context, the error field
  1037. * in the context will be set.
  1038. */
  1039. static void *__redisBlockForReply(redisContext *c) {
  1040. void *reply;
  1041. if (c->flags & REDIS_BLOCK) {
  1042. if (redisGetReply(c,&reply) != REDIS_OK)
  1043. return NULL;
  1044. return reply;
  1045. }
  1046. return NULL;
  1047. }
  1048. void *redisvCommand(redisContext *c, const char *format, va_list ap) {
  1049. if (redisvAppendCommand(c,format,ap) != REDIS_OK)
  1050. return NULL;
  1051. return __redisBlockForReply(c);
  1052. }
  1053. void *redisCommand(redisContext *c, const char *format, ...) {
  1054. va_list ap;
  1055. void *reply = NULL;
  1056. va_start(ap,format);
  1057. reply = redisvCommand(c,format,ap);
  1058. va_end(ap);
  1059. return reply;
  1060. }
  1061. void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen) {
  1062. if (redisAppendCommandArgv(c,argc,argv,argvlen) != REDIS_OK)
  1063. return NULL;
  1064. return __redisBlockForReply(c);
  1065. }