async.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 <stdlib.h>
  33. #include <string.h>
  34. #include <strings.h>
  35. #include <assert.h>
  36. #include <ctype.h>
  37. #include <errno.h>
  38. #include "async.h"
  39. #include "net.h"
  40. #include "dict.c"
  41. #include "sds.h"
  42. #define _EL_ADD_READ(ctx) do { \
  43. if ((ctx)->ev.addRead) (ctx)->ev.addRead((ctx)->ev.data); \
  44. } while(0)
  45. #define _EL_DEL_READ(ctx) do { \
  46. if ((ctx)->ev.delRead) (ctx)->ev.delRead((ctx)->ev.data); \
  47. } while(0)
  48. #define _EL_ADD_WRITE(ctx) do { \
  49. if ((ctx)->ev.addWrite) (ctx)->ev.addWrite((ctx)->ev.data); \
  50. } while(0)
  51. #define _EL_DEL_WRITE(ctx) do { \
  52. if ((ctx)->ev.delWrite) (ctx)->ev.delWrite((ctx)->ev.data); \
  53. } while(0)
  54. #define _EL_CLEANUP(ctx) do { \
  55. if ((ctx)->ev.cleanup) (ctx)->ev.cleanup((ctx)->ev.data); \
  56. } while(0);
  57. /* Forward declaration of function in hiredis.c */
  58. void __redisAppendCommand(redisContext *c, char *cmd, size_t len);
  59. /* Functions managing dictionary of callbacks for pub/sub. */
  60. static unsigned int callbackHash(const void *key) {
  61. return dictGenHashFunction((const unsigned char *)key,
  62. sdslen((const sds)key));
  63. }
  64. static void *callbackValDup(void *privdata, const void *src) {
  65. ((void) privdata);
  66. redisCallback *dup = malloc(sizeof(*dup));
  67. memcpy(dup,src,sizeof(*dup));
  68. return dup;
  69. }
  70. static int callbackKeyCompare(void *privdata, const void *key1, const void *key2) {
  71. int l1, l2;
  72. ((void) privdata);
  73. l1 = sdslen((const sds)key1);
  74. l2 = sdslen((const sds)key2);
  75. if (l1 != l2) return 0;
  76. return memcmp(key1,key2,l1) == 0;
  77. }
  78. static void callbackKeyDestructor(void *privdata, void *key) {
  79. ((void) privdata);
  80. sdsfree((sds)key);
  81. }
  82. static void callbackValDestructor(void *privdata, void *val) {
  83. ((void) privdata);
  84. free(val);
  85. }
  86. static dictType callbackDict = {
  87. callbackHash,
  88. NULL,
  89. callbackValDup,
  90. callbackKeyCompare,
  91. callbackKeyDestructor,
  92. callbackValDestructor
  93. };
  94. static redisAsyncContext *redisAsyncInitialize(redisContext *c) {
  95. redisAsyncContext *ac;
  96. ac = realloc(c,sizeof(redisAsyncContext));
  97. if (ac == NULL)
  98. return NULL;
  99. c = &(ac->c);
  100. /* The regular connect functions will always set the flag REDIS_CONNECTED.
  101. * For the async API, we want to wait until the first write event is
  102. * received up before setting this flag, so reset it here. */
  103. c->flags &= ~REDIS_CONNECTED;
  104. ac->err = 0;
  105. ac->errstr = NULL;
  106. ac->data = NULL;
  107. ac->ev.data = NULL;
  108. ac->ev.addRead = NULL;
  109. ac->ev.delRead = NULL;
  110. ac->ev.addWrite = NULL;
  111. ac->ev.delWrite = NULL;
  112. ac->ev.cleanup = NULL;
  113. ac->onConnect = NULL;
  114. ac->onDisconnect = NULL;
  115. ac->replies.head = NULL;
  116. ac->replies.tail = NULL;
  117. ac->sub.invalid.head = NULL;
  118. ac->sub.invalid.tail = NULL;
  119. ac->sub.channels = dictCreate(&callbackDict,NULL);
  120. ac->sub.patterns = dictCreate(&callbackDict,NULL);
  121. return ac;
  122. }
  123. /* We want the error field to be accessible directly instead of requiring
  124. * an indirection to the redisContext struct. */
  125. static void __redisAsyncCopyError(redisAsyncContext *ac) {
  126. redisContext *c = &(ac->c);
  127. ac->err = c->err;
  128. ac->errstr = c->errstr;
  129. }
  130. redisAsyncContext *redisAsyncConnect(const char *ip, int port) {
  131. redisContext *c;
  132. redisAsyncContext *ac;
  133. c = redisConnectNonBlock(ip,port);
  134. if (c == NULL)
  135. return NULL;
  136. ac = redisAsyncInitialize(c);
  137. if (ac == NULL) {
  138. redisFree(c);
  139. return NULL;
  140. }
  141. __redisAsyncCopyError(ac);
  142. return ac;
  143. }
  144. redisAsyncContext *redisAsyncConnectBind(const char *ip, int port,
  145. const char *source_addr) {
  146. redisContext *c = redisConnectBindNonBlock(ip,port,source_addr);
  147. redisAsyncContext *ac = redisAsyncInitialize(c);
  148. __redisAsyncCopyError(ac);
  149. return ac;
  150. }
  151. redisAsyncContext *redisAsyncConnectUnix(const char *path) {
  152. redisContext *c;
  153. redisAsyncContext *ac;
  154. c = redisConnectUnixNonBlock(path);
  155. if (c == NULL)
  156. return NULL;
  157. ac = redisAsyncInitialize(c);
  158. if (ac == NULL) {
  159. redisFree(c);
  160. return NULL;
  161. }
  162. __redisAsyncCopyError(ac);
  163. return ac;
  164. }
  165. int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn) {
  166. if (ac->onConnect == NULL) {
  167. ac->onConnect = fn;
  168. /* The common way to detect an established connection is to wait for
  169. * the first write event to be fired. This assumes the related event
  170. * library functions are already set. */
  171. _EL_ADD_WRITE(ac);
  172. return REDIS_OK;
  173. }
  174. return REDIS_ERR;
  175. }
  176. int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn) {
  177. if (ac->onDisconnect == NULL) {
  178. ac->onDisconnect = fn;
  179. return REDIS_OK;
  180. }
  181. return REDIS_ERR;
  182. }
  183. /* Helper functions to push/shift callbacks */
  184. static int __redisPushCallback(redisCallbackList *list, redisCallback *source) {
  185. redisCallback *cb;
  186. /* Copy callback from stack to heap */
  187. cb = malloc(sizeof(*cb));
  188. if (cb == NULL)
  189. return REDIS_ERR_OOM;
  190. if (source != NULL) {
  191. memcpy(cb,source,sizeof(*cb));
  192. cb->next = NULL;
  193. }
  194. /* Store callback in list */
  195. if (list->head == NULL)
  196. list->head = cb;
  197. if (list->tail != NULL)
  198. list->tail->next = cb;
  199. list->tail = cb;
  200. return REDIS_OK;
  201. }
  202. static int __redisShiftCallback(redisCallbackList *list, redisCallback *target) {
  203. redisCallback *cb = list->head;
  204. if (cb != NULL) {
  205. list->head = cb->next;
  206. if (cb == list->tail)
  207. list->tail = NULL;
  208. /* Copy callback from heap to stack */
  209. if (target != NULL)
  210. memcpy(target,cb,sizeof(*cb));
  211. free(cb);
  212. return REDIS_OK;
  213. }
  214. return REDIS_ERR;
  215. }
  216. static void __redisRunCallback(redisAsyncContext *ac, redisCallback *cb, redisReply *reply) {
  217. redisContext *c = &(ac->c);
  218. if (cb->fn != NULL) {
  219. c->flags |= REDIS_IN_CALLBACK;
  220. cb->fn(ac,reply,cb->privdata);
  221. c->flags &= ~REDIS_IN_CALLBACK;
  222. }
  223. }
  224. /* Helper function to free the context. */
  225. static void __redisAsyncFree(redisAsyncContext *ac) {
  226. redisContext *c = &(ac->c);
  227. redisCallback cb;
  228. dictIterator *it;
  229. dictEntry *de;
  230. /* Execute pending callbacks with NULL reply. */
  231. while (__redisShiftCallback(&ac->replies,&cb) == REDIS_OK)
  232. __redisRunCallback(ac,&cb,NULL);
  233. /* Execute callbacks for invalid commands */
  234. while (__redisShiftCallback(&ac->sub.invalid,&cb) == REDIS_OK)
  235. __redisRunCallback(ac,&cb,NULL);
  236. /* Run subscription callbacks callbacks with NULL reply */
  237. it = dictGetIterator(ac->sub.channels);
  238. while ((de = dictNext(it)) != NULL)
  239. __redisRunCallback(ac,dictGetEntryVal(de),NULL);
  240. dictReleaseIterator(it);
  241. dictRelease(ac->sub.channels);
  242. it = dictGetIterator(ac->sub.patterns);
  243. while ((de = dictNext(it)) != NULL)
  244. __redisRunCallback(ac,dictGetEntryVal(de),NULL);
  245. dictReleaseIterator(it);
  246. dictRelease(ac->sub.patterns);
  247. /* Signal event lib to clean up */
  248. _EL_CLEANUP(ac);
  249. /* Execute disconnect callback. When redisAsyncFree() initiated destroying
  250. * this context, the status will always be REDIS_OK. */
  251. if (ac->onDisconnect && (c->flags & REDIS_CONNECTED)) {
  252. if (c->flags & REDIS_FREEING) {
  253. ac->onDisconnect(ac,REDIS_OK);
  254. } else {
  255. ac->onDisconnect(ac,(ac->err == 0) ? REDIS_OK : REDIS_ERR);
  256. }
  257. }
  258. /* Cleanup self */
  259. redisFree(c);
  260. }
  261. /* Free the async context. When this function is called from a callback,
  262. * control needs to be returned to redisProcessCallbacks() before actual
  263. * free'ing. To do so, a flag is set on the context which is picked up by
  264. * redisProcessCallbacks(). Otherwise, the context is immediately free'd. */
  265. void redisAsyncFree(redisAsyncContext *ac) {
  266. redisContext *c = &(ac->c);
  267. c->flags |= REDIS_FREEING;
  268. if (!(c->flags & REDIS_IN_CALLBACK))
  269. __redisAsyncFree(ac);
  270. }
  271. /* Helper function to make the disconnect happen and clean up. */
  272. static void __redisAsyncDisconnect(redisAsyncContext *ac) {
  273. redisContext *c = &(ac->c);
  274. /* Make sure error is accessible if there is any */
  275. __redisAsyncCopyError(ac);
  276. if (ac->err == 0) {
  277. /* For clean disconnects, there should be no pending callbacks. */
  278. assert(__redisShiftCallback(&ac->replies,NULL) == REDIS_ERR);
  279. } else {
  280. /* Disconnection is caused by an error, make sure that pending
  281. * callbacks cannot call new commands. */
  282. c->flags |= REDIS_DISCONNECTING;
  283. }
  284. /* For non-clean disconnects, __redisAsyncFree() will execute pending
  285. * callbacks with a NULL-reply. */
  286. __redisAsyncFree(ac);
  287. }
  288. /* Tries to do a clean disconnect from Redis, meaning it stops new commands
  289. * from being issued, but tries to flush the output buffer and execute
  290. * callbacks for all remaining replies. When this function is called from a
  291. * callback, there might be more replies and we can safely defer disconnecting
  292. * to redisProcessCallbacks(). Otherwise, we can only disconnect immediately
  293. * when there are no pending callbacks. */
  294. void redisAsyncDisconnect(redisAsyncContext *ac) {
  295. redisContext *c = &(ac->c);
  296. c->flags |= REDIS_DISCONNECTING;
  297. if (!(c->flags & REDIS_IN_CALLBACK) && ac->replies.head == NULL)
  298. __redisAsyncDisconnect(ac);
  299. }
  300. static int __redisGetSubscribeCallback(redisAsyncContext *ac, redisReply *reply, redisCallback *dstcb) {
  301. redisContext *c = &(ac->c);
  302. dict *callbacks;
  303. dictEntry *de;
  304. int pvariant;
  305. char *stype;
  306. sds sname;
  307. /* Custom reply functions are not supported for pub/sub. This will fail
  308. * very hard when they are used... */
  309. if (reply->type == REDIS_REPLY_ARRAY) {
  310. assert(reply->elements >= 2);
  311. assert(reply->element[0]->type == REDIS_REPLY_STRING);
  312. stype = reply->element[0]->str;
  313. pvariant = (tolower(stype[0]) == 'p') ? 1 : 0;
  314. if (pvariant)
  315. callbacks = ac->sub.patterns;
  316. else
  317. callbacks = ac->sub.channels;
  318. /* Locate the right callback */
  319. assert(reply->element[1]->type == REDIS_REPLY_STRING);
  320. sname = sdsnewlen(reply->element[1]->str,reply->element[1]->len);
  321. de = dictFind(callbacks,sname);
  322. if (de != NULL) {
  323. memcpy(dstcb,dictGetEntryVal(de),sizeof(*dstcb));
  324. /* If this is an unsubscribe message, remove it. */
  325. if (strcasecmp(stype+pvariant,"unsubscribe") == 0) {
  326. dictDelete(callbacks,sname);
  327. /* If this was the last unsubscribe message, revert to
  328. * non-subscribe mode. */
  329. assert(reply->element[2]->type == REDIS_REPLY_INTEGER);
  330. if (reply->element[2]->integer == 0)
  331. c->flags &= ~REDIS_SUBSCRIBED;
  332. }
  333. }
  334. sdsfree(sname);
  335. } else {
  336. /* Shift callback for invalid commands. */
  337. __redisShiftCallback(&ac->sub.invalid,dstcb);
  338. }
  339. return REDIS_OK;
  340. }
  341. void redisProcessCallbacks(redisAsyncContext *ac) {
  342. redisContext *c = &(ac->c);
  343. redisCallback cb = {NULL, NULL, NULL};
  344. void *reply = NULL;
  345. int status;
  346. while((status = redisGetReply(c,&reply)) == REDIS_OK) {
  347. if (reply == NULL) {
  348. /* When the connection is being disconnected and there are
  349. * no more replies, this is the cue to really disconnect. */
  350. if (c->flags & REDIS_DISCONNECTING && sdslen(c->obuf) == 0) {
  351. __redisAsyncDisconnect(ac);
  352. return;
  353. }
  354. /* If monitor mode, repush callback */
  355. if(c->flags & REDIS_MONITORING) {
  356. __redisPushCallback(&ac->replies,&cb);
  357. }
  358. /* When the connection is not being disconnected, simply stop
  359. * trying to get replies and wait for the next loop tick. */
  360. break;
  361. }
  362. /* Even if the context is subscribed, pending regular callbacks will
  363. * get a reply before pub/sub messages arrive. */
  364. if (__redisShiftCallback(&ac->replies,&cb) != REDIS_OK) {
  365. /*
  366. * A spontaneous reply in a not-subscribed context can be the error
  367. * reply that is sent when a new connection exceeds the maximum
  368. * number of allowed connections on the server side.
  369. *
  370. * This is seen as an error instead of a regular reply because the
  371. * server closes the connection after sending it.
  372. *
  373. * To prevent the error from being overwritten by an EOF error the
  374. * connection is closed here. See issue #43.
  375. *
  376. * Another possibility is that the server is loading its dataset.
  377. * In this case we also want to close the connection, and have the
  378. * user wait until the server is ready to take our request.
  379. */
  380. if (((redisReply*)reply)->type == REDIS_REPLY_ERROR) {
  381. c->err = REDIS_ERR_OTHER;
  382. snprintf(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str);
  383. __redisAsyncDisconnect(ac);
  384. return;
  385. }
  386. /* No more regular callbacks and no errors, the context *must* be subscribed or monitoring. */
  387. assert((c->flags & REDIS_SUBSCRIBED || c->flags & REDIS_MONITORING));
  388. if(c->flags & REDIS_SUBSCRIBED)
  389. __redisGetSubscribeCallback(ac,reply,&cb);
  390. }
  391. if (cb.fn != NULL) {
  392. __redisRunCallback(ac,&cb,reply);
  393. c->reader->fn->freeObject(reply);
  394. /* Proceed with free'ing when redisAsyncFree() was called. */
  395. if (c->flags & REDIS_FREEING) {
  396. __redisAsyncFree(ac);
  397. return;
  398. }
  399. } else {
  400. /* No callback for this reply. This can either be a NULL callback,
  401. * or there were no callbacks to begin with. Either way, don't
  402. * abort with an error, but simply ignore it because the client
  403. * doesn't know what the server will spit out over the wire. */
  404. c->reader->fn->freeObject(reply);
  405. }
  406. }
  407. /* Disconnect when there was an error reading the reply */
  408. if (status != REDIS_OK)
  409. __redisAsyncDisconnect(ac);
  410. }
  411. /* Internal helper function to detect socket status the first time a read or
  412. * write event fires. When connecting was not succesful, the connect callback
  413. * is called with a REDIS_ERR status and the context is free'd. */
  414. static int __redisAsyncHandleConnect(redisAsyncContext *ac) {
  415. redisContext *c = &(ac->c);
  416. if (redisCheckSocketError(c) == REDIS_ERR) {
  417. /* Try again later when connect(2) is still in progress. */
  418. if (errno == EINPROGRESS)
  419. return REDIS_OK;
  420. if (ac->onConnect) ac->onConnect(ac,REDIS_ERR);
  421. __redisAsyncDisconnect(ac);
  422. return REDIS_ERR;
  423. }
  424. /* Mark context as connected. */
  425. c->flags |= REDIS_CONNECTED;
  426. if (ac->onConnect) ac->onConnect(ac,REDIS_OK);
  427. return REDIS_OK;
  428. }
  429. /* This function should be called when the socket is readable.
  430. * It processes all replies that can be read and executes their callbacks.
  431. */
  432. void redisAsyncHandleRead(redisAsyncContext *ac) {
  433. redisContext *c = &(ac->c);
  434. if (!(c->flags & REDIS_CONNECTED)) {
  435. /* Abort connect was not successful. */
  436. if (__redisAsyncHandleConnect(ac) != REDIS_OK)
  437. return;
  438. /* Try again later when the context is still not connected. */
  439. if (!(c->flags & REDIS_CONNECTED))
  440. return;
  441. }
  442. if (redisBufferRead(c) == REDIS_ERR) {
  443. __redisAsyncDisconnect(ac);
  444. } else {
  445. /* Always re-schedule reads */
  446. _EL_ADD_READ(ac);
  447. redisProcessCallbacks(ac);
  448. }
  449. }
  450. void redisAsyncHandleWrite(redisAsyncContext *ac) {
  451. redisContext *c = &(ac->c);
  452. int done = 0;
  453. if (!(c->flags & REDIS_CONNECTED)) {
  454. /* Abort connect was not successful. */
  455. if (__redisAsyncHandleConnect(ac) != REDIS_OK)
  456. return;
  457. /* Try again later when the context is still not connected. */
  458. if (!(c->flags & REDIS_CONNECTED))
  459. return;
  460. }
  461. if (redisBufferWrite(c,&done) == REDIS_ERR) {
  462. __redisAsyncDisconnect(ac);
  463. } else {
  464. /* Continue writing when not done, stop writing otherwise */
  465. if (!done)
  466. _EL_ADD_WRITE(ac);
  467. else
  468. _EL_DEL_WRITE(ac);
  469. /* Always schedule reads after writes */
  470. _EL_ADD_READ(ac);
  471. }
  472. }
  473. /* Sets a pointer to the first argument and its length starting at p. Returns
  474. * the number of bytes to skip to get to the following argument. */
  475. static char *nextArgument(char *start, char **str, size_t *len) {
  476. char *p = start;
  477. if (p[0] != '$') {
  478. p = strchr(p,'$');
  479. if (p == NULL) return NULL;
  480. }
  481. *len = (int)strtol(p+1,NULL,10);
  482. p = strchr(p,'\r');
  483. assert(p);
  484. *str = p+2;
  485. return p+2+(*len)+2;
  486. }
  487. /* Helper function for the redisAsyncCommand* family of functions. Writes a
  488. * formatted command to the output buffer and registers the provided callback
  489. * function with the context. */
  490. static int __redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, char *cmd, size_t len) {
  491. redisContext *c = &(ac->c);
  492. redisCallback cb;
  493. int pvariant, hasnext;
  494. char *cstr, *astr;
  495. size_t clen, alen;
  496. char *p;
  497. sds sname;
  498. /* Don't accept new commands when the connection is about to be closed. */
  499. if (c->flags & (REDIS_DISCONNECTING | REDIS_FREEING)) return REDIS_ERR;
  500. /* Setup callback */
  501. cb.fn = fn;
  502. cb.privdata = privdata;
  503. /* Find out which command will be appended. */
  504. p = nextArgument(cmd,&cstr,&clen);
  505. assert(p != NULL);
  506. hasnext = (p[0] == '$');
  507. pvariant = (tolower(cstr[0]) == 'p') ? 1 : 0;
  508. cstr += pvariant;
  509. clen -= pvariant;
  510. if (hasnext && strncasecmp(cstr,"subscribe\r\n",11) == 0) {
  511. c->flags |= REDIS_SUBSCRIBED;
  512. /* Add every channel/pattern to the list of subscription callbacks. */
  513. while ((p = nextArgument(p,&astr,&alen)) != NULL) {
  514. sname = sdsnewlen(astr,alen);
  515. if (pvariant)
  516. dictReplace(ac->sub.patterns,sname,&cb);
  517. else
  518. dictReplace(ac->sub.channels,sname,&cb);
  519. }
  520. } else if (strncasecmp(cstr,"unsubscribe\r\n",13) == 0) {
  521. /* It is only useful to call (P)UNSUBSCRIBE when the context is
  522. * subscribed to one or more channels or patterns. */
  523. if (!(c->flags & REDIS_SUBSCRIBED)) return REDIS_ERR;
  524. /* (P)UNSUBSCRIBE does not have its own response: every channel or
  525. * pattern that is unsubscribed will receive a message. This means we
  526. * should not append a callback function for this command. */
  527. } else if(strncasecmp(cstr,"monitor\r\n",9) == 0) {
  528. /* Set monitor flag and push callback */
  529. c->flags |= REDIS_MONITORING;
  530. __redisPushCallback(&ac->replies,&cb);
  531. } else {
  532. if (c->flags & REDIS_SUBSCRIBED)
  533. /* This will likely result in an error reply, but it needs to be
  534. * received and passed to the callback. */
  535. __redisPushCallback(&ac->sub.invalid,&cb);
  536. else
  537. __redisPushCallback(&ac->replies,&cb);
  538. }
  539. __redisAppendCommand(c,cmd,len);
  540. /* Always schedule a write when the write buffer is non-empty */
  541. _EL_ADD_WRITE(ac);
  542. return REDIS_OK;
  543. }
  544. int redisvAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, va_list ap) {
  545. char *cmd;
  546. int len;
  547. int status;
  548. len = redisvFormatCommand(&cmd,format,ap);
  549. status = __redisAsyncCommand(ac,fn,privdata,cmd,len);
  550. free(cmd);
  551. return status;
  552. }
  553. int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, const char *format, ...) {
  554. va_list ap;
  555. int status;
  556. va_start(ap,format);
  557. status = redisvAsyncCommand(ac,fn,privdata,format,ap);
  558. va_end(ap);
  559. return status;
  560. }
  561. int redisAsyncCommandArgv(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata, int argc, const char **argv, const size_t *argvlen) {
  562. char *cmd;
  563. int len;
  564. int status;
  565. len = redisFormatCommandArgv(&cmd,argc,argv,argvlen);
  566. status = __redisAsyncCommand(ac,fn,privdata,cmd,len);
  567. free(cmd);
  568. return status;
  569. }