async.c 23 KB

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