hiredis.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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 > 2 */
  387. if (r->ridx == 8) {
  388. __redisReaderSetError(r,REDIS_ERR_PROTOCOL,
  389. "No support for nested multi bulk replies with depth > 7");
  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. #if 0
  512. /* Destroy internal buffer when it is empty and is quite large. */
  513. if (r->len == 0 && sdsavail(r->buf) > 16*1024) {
  514. sdsfree(r->buf);
  515. r->buf = sdsempty();
  516. r->pos = 0;
  517. /* r->buf should not be NULL since we just free'd a larger one. */
  518. assert(r->buf != NULL);
  519. }
  520. #endif
  521. newbuf = sdscatlen(r->buf,buf,len);
  522. if (newbuf == NULL) {
  523. __redisReaderSetErrorOOM(r);
  524. return REDIS_ERR;
  525. }
  526. r->buf = newbuf;
  527. r->len = sdslen(r->buf);
  528. }
  529. return REDIS_OK;
  530. }
  531. int redisReaderGetReply(redisReader *r, void **reply) {
  532. /* Default target pointer to NULL. */
  533. if (reply != NULL)
  534. *reply = NULL;
  535. /* Return early when this reader is in an erroneous state. */
  536. if (r->err)
  537. return REDIS_ERR;
  538. /* When the buffer is empty, there will never be a reply. */
  539. if (r->len == 0)
  540. return REDIS_OK;
  541. /* Set first item to process when the stack is empty. */
  542. if (r->ridx == -1) {
  543. r->rstack[0].type = -1;
  544. r->rstack[0].elements = -1;
  545. r->rstack[0].idx = -1;
  546. r->rstack[0].obj = NULL;
  547. r->rstack[0].parent = NULL;
  548. r->rstack[0].privdata = r->privdata;
  549. r->ridx = 0;
  550. }
  551. /* Process items in reply. */
  552. while (r->ridx >= 0)
  553. if (processItem(r) != REDIS_OK)
  554. break;
  555. /* Return ASAP when an error occurred. */
  556. if (r->err)
  557. return REDIS_ERR;
  558. /* Discard part of the buffer when we've consumed at least 1k, to avoid
  559. * doing unnecessary calls to memmove() in sds.c. */
  560. if (r->pos >= 1024) {
  561. r->buf = sdsrange(r->buf,r->pos,-1);
  562. r->pos = 0;
  563. r->len = sdslen(r->buf);
  564. }
  565. /* Emit a reply when there is one. */
  566. if (r->ridx == -1) {
  567. if (reply != NULL)
  568. *reply = r->reply;
  569. r->reply = NULL;
  570. }
  571. return REDIS_OK;
  572. }
  573. /* Calculate the number of bytes needed to represent an integer as string. */
  574. static int intlen(int i) {
  575. int len = 0;
  576. if (i < 0) {
  577. len++;
  578. i = -i;
  579. }
  580. do {
  581. len++;
  582. i /= 10;
  583. } while(i);
  584. return len;
  585. }
  586. /* Helper that calculates the bulk length given a certain string length. */
  587. static size_t bulklen(size_t len) {
  588. return 1+intlen(len)+2+len+2;
  589. }
  590. int redisvFormatCommand(char **target, const char *format, va_list ap) {
  591. const char *c = format;
  592. char *cmd = NULL; /* final command */
  593. int pos; /* position in final command */
  594. sds curarg, newarg; /* current argument */
  595. int touched = 0; /* was the current argument touched? */
  596. char **curargv = NULL, **newargv = NULL;
  597. int argc = 0;
  598. int totlen = 0;
  599. int j;
  600. /* Abort if there is not target to set */
  601. if (target == NULL)
  602. return -1;
  603. /* Build the command string accordingly to protocol */
  604. curarg = sdsempty();
  605. if (curarg == NULL)
  606. return -1;
  607. while(*c != '\0') {
  608. if (*c != '%' || c[1] == '\0') {
  609. if (*c == ' ') {
  610. if (touched) {
  611. newargv = realloc(curargv,sizeof(char*)*(argc+1));
  612. if (newargv == NULL) goto err;
  613. curargv = newargv;
  614. curargv[argc++] = curarg;
  615. totlen += bulklen(sdslen(curarg));
  616. /* curarg is put in argv so it can be overwritten. */
  617. curarg = sdsempty();
  618. if (curarg == NULL) goto err;
  619. touched = 0;
  620. }
  621. } else {
  622. newarg = sdscatlen(curarg,c,1);
  623. if (newarg == NULL) goto err;
  624. curarg = newarg;
  625. touched = 1;
  626. }
  627. } else {
  628. char *arg;
  629. size_t size;
  630. /* Set newarg so it can be checked even if it is not touched. */
  631. newarg = curarg;
  632. switch(c[1]) {
  633. case 's':
  634. arg = va_arg(ap,char*);
  635. size = strlen(arg);
  636. if (size > 0)
  637. newarg = sdscatlen(curarg,arg,size);
  638. break;
  639. case 'b':
  640. arg = va_arg(ap,char*);
  641. size = va_arg(ap,size_t);
  642. if (size > 0)
  643. newarg = sdscatlen(curarg,arg,size);
  644. break;
  645. case '%':
  646. newarg = sdscat(curarg,"%");
  647. break;
  648. default:
  649. /* Try to detect printf format */
  650. {
  651. static const char intfmts[] = "diouxX";
  652. char _format[16];
  653. const char *_p = c+1;
  654. size_t _l = 0;
  655. va_list _cpy;
  656. /* Flags */
  657. if (*_p != '\0' && *_p == '#') _p++;
  658. if (*_p != '\0' && *_p == '0') _p++;
  659. if (*_p != '\0' && *_p == '-') _p++;
  660. if (*_p != '\0' && *_p == ' ') _p++;
  661. if (*_p != '\0' && *_p == '+') _p++;
  662. /* Field width */
  663. while (*_p != '\0' && isdigit(*_p)) _p++;
  664. /* Precision */
  665. if (*_p == '.') {
  666. _p++;
  667. while (*_p != '\0' && isdigit(*_p)) _p++;
  668. }
  669. /* Copy va_list before consuming with va_arg */
  670. va_copy(_cpy,ap);
  671. /* Integer conversion (without modifiers) */
  672. if (strchr(intfmts,*_p) != NULL) {
  673. va_arg(ap,int);
  674. goto fmt_valid;
  675. }
  676. /* Double conversion (without modifiers) */
  677. if (strchr("eEfFgGaA",*_p) != NULL) {
  678. va_arg(ap,double);
  679. goto fmt_valid;
  680. }
  681. /* Size: char */
  682. if (_p[0] == 'h' && _p[1] == 'h') {
  683. _p += 2;
  684. if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  685. va_arg(ap,int); /* char gets promoted to int */
  686. goto fmt_valid;
  687. }
  688. goto fmt_invalid;
  689. }
  690. /* Size: short */
  691. if (_p[0] == 'h') {
  692. _p += 1;
  693. if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  694. va_arg(ap,int); /* short gets promoted to int */
  695. goto fmt_valid;
  696. }
  697. goto fmt_invalid;
  698. }
  699. /* Size: long long */
  700. if (_p[0] == 'l' && _p[1] == 'l') {
  701. _p += 2;
  702. if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  703. va_arg(ap,long long);
  704. goto fmt_valid;
  705. }
  706. goto fmt_invalid;
  707. }
  708. /* Size: long */
  709. if (_p[0] == 'l') {
  710. _p += 1;
  711. if (*_p != '\0' && strchr(intfmts,*_p) != NULL) {
  712. va_arg(ap,long);
  713. goto fmt_valid;
  714. }
  715. goto fmt_invalid;
  716. }
  717. fmt_invalid:
  718. va_end(_cpy);
  719. goto err;
  720. fmt_valid:
  721. _l = (_p+1)-c;
  722. if (_l < sizeof(_format)-2) {
  723. memcpy(_format,c,_l);
  724. _format[_l] = '\0';
  725. newarg = sdscatvprintf(curarg,_format,_cpy);
  726. /* Update current position (note: outer blocks
  727. * increment c twice so compensate here) */
  728. c = _p-1;
  729. }
  730. va_end(_cpy);
  731. break;
  732. }
  733. }
  734. if (newarg == NULL) goto err;
  735. curarg = newarg;
  736. touched = 1;
  737. c++;
  738. }
  739. c++;
  740. }
  741. /* Add the last argument if needed */
  742. if (touched) {
  743. newargv = realloc(curargv,sizeof(char*)*(argc+1));
  744. if (newargv == NULL) goto err;
  745. curargv = newargv;
  746. curargv[argc++] = curarg;
  747. totlen += bulklen(sdslen(curarg));
  748. } else {
  749. sdsfree(curarg);
  750. }
  751. /* Clear curarg because it was put in curargv or was free'd. */
  752. curarg = NULL;
  753. /* Add bytes needed to hold multi bulk count */
  754. totlen += 1+intlen(argc)+2;
  755. /* Build the command at protocol level */
  756. cmd = malloc(totlen+1);
  757. if (cmd == NULL) goto err;
  758. pos = sprintf(cmd,"*%d\r\n",argc);
  759. for (j = 0; j < argc; j++) {
  760. pos += sprintf(cmd+pos,"$%zu\r\n",sdslen(curargv[j]));
  761. memcpy(cmd+pos,curargv[j],sdslen(curargv[j]));
  762. pos += sdslen(curargv[j]);
  763. sdsfree(curargv[j]);
  764. cmd[pos++] = '\r';
  765. cmd[pos++] = '\n';
  766. }
  767. assert(pos == totlen);
  768. cmd[pos] = '\0';
  769. free(curargv);
  770. *target = cmd;
  771. return totlen;
  772. err:
  773. while(argc--)
  774. sdsfree(curargv[argc]);
  775. free(curargv);
  776. if (curarg != NULL)
  777. sdsfree(curarg);
  778. /* No need to check cmd since it is the last statement that can fail,
  779. * but do it anyway to be as defensive as possible. */
  780. if (cmd != NULL)
  781. free(cmd);
  782. return -1;
  783. }
  784. /* Format a command according to the Redis protocol. This function
  785. * takes a format similar to printf:
  786. *
  787. * %s represents a C null terminated string you want to interpolate
  788. * %b represents a binary safe string
  789. *
  790. * When using %b you need to provide both the pointer to the string
  791. * and the length in bytes. Examples:
  792. *
  793. * len = redisFormatCommand(target, "GET %s", mykey);
  794. * len = redisFormatCommand(target, "SET %s %b", mykey, myval, myvallen);
  795. */
  796. int redisFormatCommand(char **target, const char *format, ...) {
  797. va_list ap;
  798. int len;
  799. va_start(ap,format);
  800. len = redisvFormatCommand(target,format,ap);
  801. va_end(ap);
  802. return len;
  803. }
  804. /* Format a command according to the Redis protocol. This function takes the
  805. * number of arguments, an array with arguments and an array with their
  806. * lengths. If the latter is set to NULL, strlen will be used to compute the
  807. * argument lengths.
  808. */
  809. int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen) {
  810. char *cmd = NULL; /* final command */
  811. int pos; /* position in final command */
  812. size_t len;
  813. int totlen, j;
  814. /* Calculate number of bytes needed for the command */
  815. totlen = 1+intlen(argc)+2;
  816. for (j = 0; j < argc; j++) {
  817. len = argvlen ? argvlen[j] : strlen(argv[j]);
  818. totlen += bulklen(len);
  819. }
  820. /* Build the command at protocol level */
  821. cmd = malloc(totlen+1);
  822. if (cmd == NULL)
  823. return -1;
  824. pos = sprintf(cmd,"*%d\r\n",argc);
  825. for (j = 0; j < argc; j++) {
  826. len = argvlen ? argvlen[j] : strlen(argv[j]);
  827. pos += sprintf(cmd+pos,"$%zu\r\n",len);
  828. memcpy(cmd+pos,argv[j],len);
  829. pos += len;
  830. cmd[pos++] = '\r';
  831. cmd[pos++] = '\n';
  832. }
  833. assert(pos == totlen);
  834. cmd[pos] = '\0';
  835. *target = cmd;
  836. return totlen;
  837. }
  838. void __redisSetError(redisContext *c, int type, const char *str) {
  839. size_t len;
  840. c->err = type;
  841. if (str != NULL) {
  842. len = strlen(str);
  843. len = len < (sizeof(c->errstr)-1) ? len : (sizeof(c->errstr)-1);
  844. memcpy(c->errstr,str,len);
  845. c->errstr[len] = '\0';
  846. } else {
  847. /* Only REDIS_ERR_IO may lack a description! */
  848. assert(type == REDIS_ERR_IO);
  849. strerror_r(errno,c->errstr,sizeof(c->errstr));
  850. }
  851. }
  852. static redisContext *redisContextInit(void) {
  853. redisContext *c;
  854. c = calloc(1,sizeof(redisContext));
  855. if (c == NULL)
  856. return NULL;
  857. c->err = 0;
  858. c->errstr[0] = '\0';
  859. c->obuf = sdsempty();
  860. c->reader = redisReaderCreate();
  861. return c;
  862. }
  863. void redisFree(redisContext *c) {
  864. if (c->fd > 0)
  865. close(c->fd);
  866. if (c->obuf != NULL)
  867. sdsfree(c->obuf);
  868. if (c->reader != NULL)
  869. redisReaderFree(c->reader);
  870. free(c);
  871. }
  872. /* Connect to a Redis instance. On error the field error in the returned
  873. * context will be set to the return value of the error function.
  874. * When no set of reply functions is given, the default set will be used. */
  875. redisContext *redisConnect(const char *ip, int port) {
  876. redisContext *c = redisContextInit();
  877. c->flags |= REDIS_BLOCK;
  878. redisContextConnectTcp(c,ip,port,NULL);
  879. return c;
  880. }
  881. redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv) {
  882. redisContext *c = redisContextInit();
  883. c->flags |= REDIS_BLOCK;
  884. redisContextConnectTcp(c,ip,port,&tv);
  885. return c;
  886. }
  887. redisContext *redisConnectNonBlock(const char *ip, int port) {
  888. redisContext *c = redisContextInit();
  889. c->flags &= ~REDIS_BLOCK;
  890. redisContextConnectTcp(c,ip,port,NULL);
  891. return c;
  892. }
  893. redisContext *redisConnectUnix(const char *path) {
  894. redisContext *c = redisContextInit();
  895. c->flags |= REDIS_BLOCK;
  896. redisContextConnectUnix(c,path,NULL);
  897. return c;
  898. }
  899. redisContext *redisConnectUnixWithTimeout(const char *path, struct timeval tv) {
  900. redisContext *c = redisContextInit();
  901. c->flags |= REDIS_BLOCK;
  902. redisContextConnectUnix(c,path,&tv);
  903. return c;
  904. }
  905. redisContext *redisConnectUnixNonBlock(const char *path) {
  906. redisContext *c = redisContextInit();
  907. c->flags &= ~REDIS_BLOCK;
  908. redisContextConnectUnix(c,path,NULL);
  909. return c;
  910. }
  911. /* Set read/write timeout on a blocking socket. */
  912. int redisSetTimeout(redisContext *c, struct timeval tv) {
  913. if (c->flags & REDIS_BLOCK)
  914. return redisContextSetTimeout(c,tv);
  915. return REDIS_ERR;
  916. }
  917. /* Use this function to handle a read event on the descriptor. It will try
  918. * and read some bytes from the socket and feed them to the reply parser.
  919. *
  920. * After this function is called, you may use redisContextReadReply to
  921. * see if there is a reply available. */
  922. int redisBufferRead(redisContext *c) {
  923. char buf[1024*16];
  924. int nread;
  925. /* Return early when the context has seen an error. */
  926. if (c->err)
  927. return REDIS_ERR;
  928. nread = read(c->fd,buf,sizeof(buf));
  929. if (nread == -1) {
  930. if (errno == EAGAIN && !(c->flags & REDIS_BLOCK)) {
  931. /* Try again later */
  932. } else {
  933. __redisSetError(c,REDIS_ERR_IO,NULL);
  934. return REDIS_ERR;
  935. }
  936. } else if (nread == 0) {
  937. __redisSetError(c,REDIS_ERR_EOF,"Server closed the connection");
  938. return REDIS_ERR;
  939. } else {
  940. if (redisReaderFeed(c->reader,buf,nread) != REDIS_OK) {
  941. __redisSetError(c,c->reader->err,c->reader->errstr);
  942. return REDIS_ERR;
  943. }
  944. }
  945. return REDIS_OK;
  946. }
  947. /* Write the output buffer to the socket.
  948. *
  949. * Returns REDIS_OK when the buffer is empty, or (a part of) the buffer was
  950. * succesfully written to the socket. When the buffer is empty after the
  951. * write operation, "done" is set to 1 (if given).
  952. *
  953. * Returns REDIS_ERR if an error occured trying to write and sets
  954. * c->errstr to hold the appropriate error string.
  955. */
  956. int redisBufferWrite(redisContext *c, int *done) {
  957. int nwritten;
  958. /* Return early when the context has seen an error. */
  959. if (c->err)
  960. return REDIS_ERR;
  961. if (sdslen(c->obuf) > 0) {
  962. nwritten = write(c->fd,c->obuf,sdslen(c->obuf));
  963. if (nwritten == -1) {
  964. if (errno == EAGAIN && !(c->flags & REDIS_BLOCK)) {
  965. /* Try again later */
  966. } else {
  967. __redisSetError(c,REDIS_ERR_IO,NULL);
  968. return REDIS_ERR;
  969. }
  970. } else if (nwritten > 0) {
  971. if (nwritten == (signed)sdslen(c->obuf)) {
  972. sdsfree(c->obuf);
  973. c->obuf = sdsempty();
  974. } else {
  975. c->obuf = sdsrange(c->obuf,nwritten,-1);
  976. }
  977. }
  978. }
  979. if (done != NULL) *done = (sdslen(c->obuf) == 0);
  980. return REDIS_OK;
  981. }
  982. /* Internal helper function to try and get a reply from the reader,
  983. * or set an error in the context otherwise. */
  984. int redisGetReplyFromReader(redisContext *c, void **reply) {
  985. if (redisReaderGetReply(c->reader,reply) == REDIS_ERR) {
  986. __redisSetError(c,c->reader->err,c->reader->errstr);
  987. return REDIS_ERR;
  988. }
  989. return REDIS_OK;
  990. }
  991. int redisGetReply(redisContext *c, void **reply) {
  992. int wdone = 0;
  993. void *aux = NULL;
  994. /* Try to read pending replies */
  995. if (redisGetReplyFromReader(c,&aux) == REDIS_ERR)
  996. return REDIS_ERR;
  997. /* For the blocking context, flush output buffer and read reply */
  998. if (aux == NULL && c->flags & REDIS_BLOCK) {
  999. /* Write until done */
  1000. do {
  1001. if (redisBufferWrite(c,&wdone) == REDIS_ERR)
  1002. return REDIS_ERR;
  1003. } while (!wdone);
  1004. /* Read until there is a reply */
  1005. do {
  1006. if (redisBufferRead(c) == REDIS_ERR)
  1007. return REDIS_ERR;
  1008. if (redisGetReplyFromReader(c,&aux) == REDIS_ERR)
  1009. return REDIS_ERR;
  1010. } while (aux == NULL);
  1011. }
  1012. /* Set reply object */
  1013. if (reply != NULL) *reply = aux;
  1014. return REDIS_OK;
  1015. }
  1016. /* Helper function for the redisAppendCommand* family of functions.
  1017. *
  1018. * Write a formatted command to the output buffer. When this family
  1019. * is used, you need to call redisGetReply yourself to retrieve
  1020. * the reply (or replies in pub/sub).
  1021. */
  1022. int __redisAppendCommand(redisContext *c, char *cmd, size_t len) {
  1023. sds newbuf;
  1024. newbuf = sdscatlen(c->obuf,cmd,len);
  1025. if (newbuf == NULL) {
  1026. __redisSetError(c,REDIS_ERR_OOM,"Out of memory");
  1027. return REDIS_ERR;
  1028. }
  1029. c->obuf = newbuf;
  1030. return REDIS_OK;
  1031. }
  1032. int redisvAppendCommand(redisContext *c, const char *format, va_list ap) {
  1033. char *cmd;
  1034. int len;
  1035. len = redisvFormatCommand(&cmd,format,ap);
  1036. if (len == -1) {
  1037. __redisSetError(c,REDIS_ERR_OOM,"Out of memory");
  1038. return REDIS_ERR;
  1039. }
  1040. if (__redisAppendCommand(c,cmd,len) != REDIS_OK) {
  1041. free(cmd);
  1042. return REDIS_ERR;
  1043. }
  1044. free(cmd);
  1045. return REDIS_OK;
  1046. }
  1047. int redisAppendCommand(redisContext *c, const char *format, ...) {
  1048. va_list ap;
  1049. int ret;
  1050. va_start(ap,format);
  1051. ret = redisvAppendCommand(c,format,ap);
  1052. va_end(ap);
  1053. return ret;
  1054. }
  1055. int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen) {
  1056. char *cmd;
  1057. int len;
  1058. len = redisFormatCommandArgv(&cmd,argc,argv,argvlen);
  1059. if (len == -1) {
  1060. __redisSetError(c,REDIS_ERR_OOM,"Out of memory");
  1061. return REDIS_ERR;
  1062. }
  1063. if (__redisAppendCommand(c,cmd,len) != REDIS_OK) {
  1064. free(cmd);
  1065. return REDIS_ERR;
  1066. }
  1067. free(cmd);
  1068. return REDIS_OK;
  1069. }
  1070. /* Helper function for the redisCommand* family of functions.
  1071. *
  1072. * Write a formatted command to the output buffer. If the given context is
  1073. * blocking, immediately read the reply into the "reply" pointer. When the
  1074. * context is non-blocking, the "reply" pointer will not be used and the
  1075. * command is simply appended to the write buffer.
  1076. *
  1077. * Returns the reply when a reply was succesfully retrieved. Returns NULL
  1078. * otherwise. When NULL is returned in a blocking context, the error field
  1079. * in the context will be set.
  1080. */
  1081. static void *__redisBlockForReply(redisContext *c) {
  1082. void *reply;
  1083. if (c->flags & REDIS_BLOCK) {
  1084. if (redisGetReply(c,&reply) != REDIS_OK)
  1085. return NULL;
  1086. return reply;
  1087. }
  1088. return NULL;
  1089. }
  1090. void *redisvCommand(redisContext *c, const char *format, va_list ap) {
  1091. if (redisvAppendCommand(c,format,ap) != REDIS_OK)
  1092. return NULL;
  1093. return __redisBlockForReply(c);
  1094. }
  1095. void *redisCommand(redisContext *c, const char *format, ...) {
  1096. va_list ap;
  1097. void *reply = NULL;
  1098. va_start(ap,format);
  1099. reply = redisvCommand(c,format,ap);
  1100. va_end(ap);
  1101. return reply;
  1102. }
  1103. void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen) {
  1104. if (redisAppendCommandArgv(c,argc,argv,argvlen) != REDIS_OK)
  1105. return NULL;
  1106. return __redisBlockForReply(c);
  1107. }