test.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. #include "fmacros.h"
  2. #include "sockcompat.h"
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #ifndef _WIN32
  7. #include <strings.h>
  8. #include <sys/time.h>
  9. #endif
  10. #include <assert.h>
  11. #include <signal.h>
  12. #include <errno.h>
  13. #include <limits.h>
  14. #include "hiredis.h"
  15. #include "async.h"
  16. #ifdef HIREDIS_TEST_SSL
  17. #include "hiredis_ssl.h"
  18. #endif
  19. #include "net.h"
  20. #include "win32.h"
  21. enum connection_type {
  22. CONN_TCP,
  23. CONN_UNIX,
  24. CONN_FD,
  25. CONN_SSL
  26. };
  27. struct config {
  28. enum connection_type type;
  29. struct {
  30. const char *host;
  31. int port;
  32. struct timeval timeout;
  33. } tcp;
  34. struct {
  35. const char *path;
  36. } unix_sock;
  37. struct {
  38. const char *host;
  39. int port;
  40. const char *ca_cert;
  41. const char *cert;
  42. const char *key;
  43. } ssl;
  44. };
  45. struct privdata {
  46. int dtor_counter;
  47. };
  48. struct pushCounters {
  49. int nil;
  50. int str;
  51. };
  52. #ifdef HIREDIS_TEST_SSL
  53. redisSSLContext *_ssl_ctx = NULL;
  54. #endif
  55. /* The following lines make up our testing "framework" :) */
  56. static int tests = 0, fails = 0, skips = 0;
  57. #define test(_s) { printf("#%02d ", ++tests); printf(_s); }
  58. #define test_cond(_c) if(_c) printf("\033[0;32mPASSED\033[0;0m\n"); else {printf("\033[0;31mFAILED\033[0;0m\n"); fails++;}
  59. #define test_skipped() { printf("\033[01;33mSKIPPED\033[0;0m\n"); skips++; }
  60. static long long usec(void) {
  61. #ifndef _MSC_VER
  62. struct timeval tv;
  63. gettimeofday(&tv,NULL);
  64. return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
  65. #else
  66. FILETIME ft;
  67. GetSystemTimeAsFileTime(&ft);
  68. return (((long long)ft.dwHighDateTime << 32) | ft.dwLowDateTime) / 10;
  69. #endif
  70. }
  71. /* The assert() calls below have side effects, so we need assert()
  72. * even if we are compiling without asserts (-DNDEBUG). */
  73. #ifdef NDEBUG
  74. #undef assert
  75. #define assert(e) (void)(e)
  76. #endif
  77. /* Helper to extract Redis version information. Aborts on any failure. */
  78. #define REDIS_VERSION_FIELD "redis_version:"
  79. void get_redis_version(redisContext *c, int *majorptr, int *minorptr) {
  80. redisReply *reply;
  81. char *eptr, *s, *e;
  82. int major, minor;
  83. reply = redisCommand(c, "INFO");
  84. if (reply == NULL || c->err || reply->type != REDIS_REPLY_STRING)
  85. goto abort;
  86. if ((s = strstr(reply->str, REDIS_VERSION_FIELD)) == NULL)
  87. goto abort;
  88. s += strlen(REDIS_VERSION_FIELD);
  89. /* We need a field terminator and at least 'x.y.z' (5) bytes of data */
  90. if ((e = strstr(s, "\r\n")) == NULL || (e - s) < 5)
  91. goto abort;
  92. /* Extract version info */
  93. major = strtol(s, &eptr, 10);
  94. if (*eptr != '.') goto abort;
  95. minor = strtol(eptr+1, NULL, 10);
  96. /* Push info the caller wants */
  97. if (majorptr) *majorptr = major;
  98. if (minorptr) *minorptr = minor;
  99. freeReplyObject(reply);
  100. return;
  101. abort:
  102. freeReplyObject(reply);
  103. fprintf(stderr, "Error: Cannot determine Redis version, aborting\n");
  104. exit(1);
  105. }
  106. static redisContext *select_database(redisContext *c) {
  107. redisReply *reply;
  108. /* Switch to DB 9 for testing, now that we know we can chat. */
  109. reply = redisCommand(c,"SELECT 9");
  110. assert(reply != NULL);
  111. freeReplyObject(reply);
  112. /* Make sure the DB is emtpy */
  113. reply = redisCommand(c,"DBSIZE");
  114. assert(reply != NULL);
  115. if (reply->type == REDIS_REPLY_INTEGER && reply->integer == 0) {
  116. /* Awesome, DB 9 is empty and we can continue. */
  117. freeReplyObject(reply);
  118. } else {
  119. printf("Database #9 is not empty, test can not continue\n");
  120. exit(1);
  121. }
  122. return c;
  123. }
  124. /* Switch protocol */
  125. static void send_hello(redisContext *c, int version) {
  126. redisReply *reply;
  127. int expected;
  128. reply = redisCommand(c, "HELLO %d", version);
  129. expected = version == 3 ? REDIS_REPLY_MAP : REDIS_REPLY_ARRAY;
  130. assert(reply != NULL && reply->type == expected);
  131. freeReplyObject(reply);
  132. }
  133. /* Togggle client tracking */
  134. static void send_client_tracking(redisContext *c, const char *str) {
  135. redisReply *reply;
  136. reply = redisCommand(c, "CLIENT TRACKING %s", str);
  137. assert(reply != NULL && reply->type == REDIS_REPLY_STATUS);
  138. freeReplyObject(reply);
  139. }
  140. static int disconnect(redisContext *c, int keep_fd) {
  141. redisReply *reply;
  142. /* Make sure we're on DB 9. */
  143. reply = redisCommand(c,"SELECT 9");
  144. assert(reply != NULL);
  145. freeReplyObject(reply);
  146. reply = redisCommand(c,"FLUSHDB");
  147. assert(reply != NULL);
  148. freeReplyObject(reply);
  149. /* Free the context as well, but keep the fd if requested. */
  150. if (keep_fd)
  151. return redisFreeKeepFd(c);
  152. redisFree(c);
  153. return -1;
  154. }
  155. static void do_ssl_handshake(redisContext *c) {
  156. #ifdef HIREDIS_TEST_SSL
  157. redisInitiateSSLWithContext(c, _ssl_ctx);
  158. if (c->err) {
  159. printf("SSL error: %s\n", c->errstr);
  160. redisFree(c);
  161. exit(1);
  162. }
  163. #else
  164. (void) c;
  165. #endif
  166. }
  167. static redisContext *do_connect(struct config config) {
  168. redisContext *c = NULL;
  169. if (config.type == CONN_TCP) {
  170. c = redisConnect(config.tcp.host, config.tcp.port);
  171. } else if (config.type == CONN_SSL) {
  172. c = redisConnect(config.ssl.host, config.ssl.port);
  173. } else if (config.type == CONN_UNIX) {
  174. c = redisConnectUnix(config.unix_sock.path);
  175. } else if (config.type == CONN_FD) {
  176. /* Create a dummy connection just to get an fd to inherit */
  177. redisContext *dummy_ctx = redisConnectUnix(config.unix_sock.path);
  178. if (dummy_ctx) {
  179. int fd = disconnect(dummy_ctx, 1);
  180. printf("Connecting to inherited fd %d\n", fd);
  181. c = redisConnectFd(fd);
  182. }
  183. } else {
  184. assert(NULL);
  185. }
  186. if (c == NULL) {
  187. printf("Connection error: can't allocate redis context\n");
  188. exit(1);
  189. } else if (c->err) {
  190. printf("Connection error: %s\n", c->errstr);
  191. redisFree(c);
  192. exit(1);
  193. }
  194. if (config.type == CONN_SSL) {
  195. do_ssl_handshake(c);
  196. }
  197. return select_database(c);
  198. }
  199. static void do_reconnect(redisContext *c, struct config config) {
  200. redisReconnect(c);
  201. if (config.type == CONN_SSL) {
  202. do_ssl_handshake(c);
  203. }
  204. }
  205. static void test_format_commands(void) {
  206. char *cmd;
  207. int len;
  208. test("Format command without interpolation: ");
  209. len = redisFormatCommand(&cmd,"SET foo bar");
  210. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
  211. len == 4+4+(3+2)+4+(3+2)+4+(3+2));
  212. hi_free(cmd);
  213. test("Format command with %%s string interpolation: ");
  214. len = redisFormatCommand(&cmd,"SET %s %s","foo","bar");
  215. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
  216. len == 4+4+(3+2)+4+(3+2)+4+(3+2));
  217. hi_free(cmd);
  218. test("Format command with %%s and an empty string: ");
  219. len = redisFormatCommand(&cmd,"SET %s %s","foo","");
  220. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 &&
  221. len == 4+4+(3+2)+4+(3+2)+4+(0+2));
  222. hi_free(cmd);
  223. test("Format command with an empty string in between proper interpolations: ");
  224. len = redisFormatCommand(&cmd,"SET %s %s","","foo");
  225. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$0\r\n\r\n$3\r\nfoo\r\n",len) == 0 &&
  226. len == 4+4+(3+2)+4+(0+2)+4+(3+2));
  227. hi_free(cmd);
  228. test("Format command with %%b string interpolation: ");
  229. len = redisFormatCommand(&cmd,"SET %b %b","foo",(size_t)3,"b\0r",(size_t)3);
  230. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nb\0r\r\n",len) == 0 &&
  231. len == 4+4+(3+2)+4+(3+2)+4+(3+2));
  232. hi_free(cmd);
  233. test("Format command with %%b and an empty string: ");
  234. len = redisFormatCommand(&cmd,"SET %b %b","foo",(size_t)3,"",(size_t)0);
  235. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$0\r\n\r\n",len) == 0 &&
  236. len == 4+4+(3+2)+4+(3+2)+4+(0+2));
  237. hi_free(cmd);
  238. test("Format command with literal %%: ");
  239. len = redisFormatCommand(&cmd,"SET %% %%");
  240. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$1\r\n%\r\n$1\r\n%\r\n",len) == 0 &&
  241. len == 4+4+(3+2)+4+(1+2)+4+(1+2));
  242. hi_free(cmd);
  243. /* Vararg width depends on the type. These tests make sure that the
  244. * width is correctly determined using the format and subsequent varargs
  245. * can correctly be interpolated. */
  246. #define INTEGER_WIDTH_TEST(fmt, type) do { \
  247. type value = 123; \
  248. test("Format command with printf-delegation (" #type "): "); \
  249. len = redisFormatCommand(&cmd,"key:%08" fmt " str:%s", value, "hello"); \
  250. test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:00000123\r\n$9\r\nstr:hello\r\n",len) == 0 && \
  251. len == 4+5+(12+2)+4+(9+2)); \
  252. hi_free(cmd); \
  253. } while(0)
  254. #define FLOAT_WIDTH_TEST(type) do { \
  255. type value = 123.0; \
  256. test("Format command with printf-delegation (" #type "): "); \
  257. len = redisFormatCommand(&cmd,"key:%08.3f str:%s", value, "hello"); \
  258. test_cond(strncmp(cmd,"*2\r\n$12\r\nkey:0123.000\r\n$9\r\nstr:hello\r\n",len) == 0 && \
  259. len == 4+5+(12+2)+4+(9+2)); \
  260. hi_free(cmd); \
  261. } while(0)
  262. INTEGER_WIDTH_TEST("d", int);
  263. INTEGER_WIDTH_TEST("hhd", char);
  264. INTEGER_WIDTH_TEST("hd", short);
  265. INTEGER_WIDTH_TEST("ld", long);
  266. INTEGER_WIDTH_TEST("lld", long long);
  267. INTEGER_WIDTH_TEST("u", unsigned int);
  268. INTEGER_WIDTH_TEST("hhu", unsigned char);
  269. INTEGER_WIDTH_TEST("hu", unsigned short);
  270. INTEGER_WIDTH_TEST("lu", unsigned long);
  271. INTEGER_WIDTH_TEST("llu", unsigned long long);
  272. FLOAT_WIDTH_TEST(float);
  273. FLOAT_WIDTH_TEST(double);
  274. test("Format command with invalid printf format: ");
  275. len = redisFormatCommand(&cmd,"key:%08p %b",(void*)1234,"foo",(size_t)3);
  276. test_cond(len == -1);
  277. const char *argv[3];
  278. argv[0] = "SET";
  279. argv[1] = "foo\0xxx";
  280. argv[2] = "bar";
  281. size_t lens[3] = { 3, 7, 3 };
  282. int argc = 3;
  283. test("Format command by passing argc/argv without lengths: ");
  284. len = redisFormatCommandArgv(&cmd,argc,argv,NULL);
  285. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
  286. len == 4+4+(3+2)+4+(3+2)+4+(3+2));
  287. hi_free(cmd);
  288. test("Format command by passing argc/argv with lengths: ");
  289. len = redisFormatCommandArgv(&cmd,argc,argv,lens);
  290. test_cond(strncmp(cmd,"*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n",len) == 0 &&
  291. len == 4+4+(3+2)+4+(7+2)+4+(3+2));
  292. hi_free(cmd);
  293. hisds sds_cmd;
  294. sds_cmd = NULL;
  295. test("Format command into hisds by passing argc/argv without lengths: ");
  296. len = redisFormatSdsCommandArgv(&sds_cmd,argc,argv,NULL);
  297. test_cond(strncmp(sds_cmd,"*3\r\n$3\r\nSET\r\n$3\r\nfoo\r\n$3\r\nbar\r\n",len) == 0 &&
  298. len == 4+4+(3+2)+4+(3+2)+4+(3+2));
  299. hi_sdsfree(sds_cmd);
  300. sds_cmd = NULL;
  301. test("Format command into hisds by passing argc/argv with lengths: ");
  302. len = redisFormatSdsCommandArgv(&sds_cmd,argc,argv,lens);
  303. test_cond(strncmp(sds_cmd,"*3\r\n$3\r\nSET\r\n$7\r\nfoo\0xxx\r\n$3\r\nbar\r\n",len) == 0 &&
  304. len == 4+4+(3+2)+4+(7+2)+4+(3+2));
  305. hi_sdsfree(sds_cmd);
  306. }
  307. static void test_append_formatted_commands(struct config config) {
  308. redisContext *c;
  309. redisReply *reply;
  310. char *cmd;
  311. int len;
  312. c = do_connect(config);
  313. test("Append format command: ");
  314. len = redisFormatCommand(&cmd, "SET foo bar");
  315. test_cond(redisAppendFormattedCommand(c, cmd, len) == REDIS_OK);
  316. assert(redisGetReply(c, (void*)&reply) == REDIS_OK);
  317. hi_free(cmd);
  318. freeReplyObject(reply);
  319. disconnect(c, 0);
  320. }
  321. static void test_reply_reader(void) {
  322. redisReader *reader;
  323. void *reply, *root;
  324. int ret;
  325. int i;
  326. test("Error handling in reply parser: ");
  327. reader = redisReaderCreate();
  328. redisReaderFeed(reader,(char*)"@foo\r\n",6);
  329. ret = redisReaderGetReply(reader,NULL);
  330. test_cond(ret == REDIS_ERR &&
  331. strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0);
  332. redisReaderFree(reader);
  333. /* when the reply already contains multiple items, they must be free'd
  334. * on an error. valgrind will bark when this doesn't happen. */
  335. test("Memory cleanup in reply parser: ");
  336. reader = redisReaderCreate();
  337. redisReaderFeed(reader,(char*)"*2\r\n",4);
  338. redisReaderFeed(reader,(char*)"$5\r\nhello\r\n",11);
  339. redisReaderFeed(reader,(char*)"@foo\r\n",6);
  340. ret = redisReaderGetReply(reader,NULL);
  341. test_cond(ret == REDIS_ERR &&
  342. strcasecmp(reader->errstr,"Protocol error, got \"@\" as reply type byte") == 0);
  343. redisReaderFree(reader);
  344. reader = redisReaderCreate();
  345. test("Can handle arbitrarily nested multi-bulks: ");
  346. for (i = 0; i < 128; i++) {
  347. redisReaderFeed(reader,(char*)"*1\r\n", 4);
  348. }
  349. redisReaderFeed(reader,(char*)"$6\r\nLOLWUT\r\n",12);
  350. ret = redisReaderGetReply(reader,&reply);
  351. root = reply; /* Keep track of the root reply */
  352. test_cond(ret == REDIS_OK &&
  353. ((redisReply*)reply)->type == REDIS_REPLY_ARRAY &&
  354. ((redisReply*)reply)->elements == 1);
  355. test("Can parse arbitrarily nested multi-bulks correctly: ");
  356. while(i--) {
  357. assert(reply != NULL && ((redisReply*)reply)->type == REDIS_REPLY_ARRAY);
  358. reply = ((redisReply*)reply)->element[0];
  359. }
  360. test_cond(((redisReply*)reply)->type == REDIS_REPLY_STRING &&
  361. !memcmp(((redisReply*)reply)->str, "LOLWUT", 6));
  362. freeReplyObject(root);
  363. redisReaderFree(reader);
  364. test("Correctly parses LLONG_MAX: ");
  365. reader = redisReaderCreate();
  366. redisReaderFeed(reader, ":9223372036854775807\r\n",22);
  367. ret = redisReaderGetReply(reader,&reply);
  368. test_cond(ret == REDIS_OK &&
  369. ((redisReply*)reply)->type == REDIS_REPLY_INTEGER &&
  370. ((redisReply*)reply)->integer == LLONG_MAX);
  371. freeReplyObject(reply);
  372. redisReaderFree(reader);
  373. test("Set error when > LLONG_MAX: ");
  374. reader = redisReaderCreate();
  375. redisReaderFeed(reader, ":9223372036854775808\r\n",22);
  376. ret = redisReaderGetReply(reader,&reply);
  377. test_cond(ret == REDIS_ERR &&
  378. strcasecmp(reader->errstr,"Bad integer value") == 0);
  379. freeReplyObject(reply);
  380. redisReaderFree(reader);
  381. test("Correctly parses LLONG_MIN: ");
  382. reader = redisReaderCreate();
  383. redisReaderFeed(reader, ":-9223372036854775808\r\n",23);
  384. ret = redisReaderGetReply(reader,&reply);
  385. test_cond(ret == REDIS_OK &&
  386. ((redisReply*)reply)->type == REDIS_REPLY_INTEGER &&
  387. ((redisReply*)reply)->integer == LLONG_MIN);
  388. freeReplyObject(reply);
  389. redisReaderFree(reader);
  390. test("Set error when < LLONG_MIN: ");
  391. reader = redisReaderCreate();
  392. redisReaderFeed(reader, ":-9223372036854775809\r\n",23);
  393. ret = redisReaderGetReply(reader,&reply);
  394. test_cond(ret == REDIS_ERR &&
  395. strcasecmp(reader->errstr,"Bad integer value") == 0);
  396. freeReplyObject(reply);
  397. redisReaderFree(reader);
  398. test("Set error when array < -1: ");
  399. reader = redisReaderCreate();
  400. redisReaderFeed(reader, "*-2\r\n+asdf\r\n",12);
  401. ret = redisReaderGetReply(reader,&reply);
  402. test_cond(ret == REDIS_ERR &&
  403. strcasecmp(reader->errstr,"Multi-bulk length out of range") == 0);
  404. freeReplyObject(reply);
  405. redisReaderFree(reader);
  406. test("Set error when bulk < -1: ");
  407. reader = redisReaderCreate();
  408. redisReaderFeed(reader, "$-2\r\nasdf\r\n",11);
  409. ret = redisReaderGetReply(reader,&reply);
  410. test_cond(ret == REDIS_ERR &&
  411. strcasecmp(reader->errstr,"Bulk string length out of range") == 0);
  412. freeReplyObject(reply);
  413. redisReaderFree(reader);
  414. test("Can configure maximum multi-bulk elements: ");
  415. reader = redisReaderCreate();
  416. reader->maxelements = 1024;
  417. redisReaderFeed(reader, "*1025\r\n", 7);
  418. ret = redisReaderGetReply(reader,&reply);
  419. test_cond(ret == REDIS_ERR &&
  420. strcasecmp(reader->errstr, "Multi-bulk length out of range") == 0);
  421. freeReplyObject(reply);
  422. redisReaderFree(reader);
  423. test("Multi-bulk never overflows regardless of maxelements: ");
  424. size_t bad_mbulk_len = (SIZE_MAX / sizeof(void *)) + 3;
  425. char bad_mbulk_reply[100];
  426. snprintf(bad_mbulk_reply, sizeof(bad_mbulk_reply), "*%llu\r\n+asdf\r\n",
  427. (unsigned long long) bad_mbulk_len);
  428. reader = redisReaderCreate();
  429. reader->maxelements = 0; /* Don't rely on default limit */
  430. redisReaderFeed(reader, bad_mbulk_reply, strlen(bad_mbulk_reply));
  431. ret = redisReaderGetReply(reader,&reply);
  432. test_cond(ret == REDIS_ERR && strcasecmp(reader->errstr, "Out of memory") == 0);
  433. freeReplyObject(reply);
  434. redisReaderFree(reader);
  435. #if LLONG_MAX > SIZE_MAX
  436. test("Set error when array > SIZE_MAX: ");
  437. reader = redisReaderCreate();
  438. redisReaderFeed(reader, "*9223372036854775807\r\n+asdf\r\n",29);
  439. ret = redisReaderGetReply(reader,&reply);
  440. test_cond(ret == REDIS_ERR &&
  441. strcasecmp(reader->errstr,"Multi-bulk length out of range") == 0);
  442. freeReplyObject(reply);
  443. redisReaderFree(reader);
  444. test("Set error when bulk > SIZE_MAX: ");
  445. reader = redisReaderCreate();
  446. redisReaderFeed(reader, "$9223372036854775807\r\nasdf\r\n",28);
  447. ret = redisReaderGetReply(reader,&reply);
  448. test_cond(ret == REDIS_ERR &&
  449. strcasecmp(reader->errstr,"Bulk string length out of range") == 0);
  450. freeReplyObject(reply);
  451. redisReaderFree(reader);
  452. #endif
  453. test("Works with NULL functions for reply: ");
  454. reader = redisReaderCreate();
  455. reader->fn = NULL;
  456. redisReaderFeed(reader,(char*)"+OK\r\n",5);
  457. ret = redisReaderGetReply(reader,&reply);
  458. test_cond(ret == REDIS_OK && reply == (void*)REDIS_REPLY_STATUS);
  459. redisReaderFree(reader);
  460. test("Works when a single newline (\\r\\n) covers two calls to feed: ");
  461. reader = redisReaderCreate();
  462. reader->fn = NULL;
  463. redisReaderFeed(reader,(char*)"+OK\r",4);
  464. ret = redisReaderGetReply(reader,&reply);
  465. assert(ret == REDIS_OK && reply == NULL);
  466. redisReaderFeed(reader,(char*)"\n",1);
  467. ret = redisReaderGetReply(reader,&reply);
  468. test_cond(ret == REDIS_OK && reply == (void*)REDIS_REPLY_STATUS);
  469. redisReaderFree(reader);
  470. test("Don't reset state after protocol error: ");
  471. reader = redisReaderCreate();
  472. reader->fn = NULL;
  473. redisReaderFeed(reader,(char*)"x",1);
  474. ret = redisReaderGetReply(reader,&reply);
  475. assert(ret == REDIS_ERR);
  476. ret = redisReaderGetReply(reader,&reply);
  477. test_cond(ret == REDIS_ERR && reply == NULL);
  478. redisReaderFree(reader);
  479. /* Regression test for issue #45 on GitHub. */
  480. test("Don't do empty allocation for empty multi bulk: ");
  481. reader = redisReaderCreate();
  482. redisReaderFeed(reader,(char*)"*0\r\n",4);
  483. ret = redisReaderGetReply(reader,&reply);
  484. test_cond(ret == REDIS_OK &&
  485. ((redisReply*)reply)->type == REDIS_REPLY_ARRAY &&
  486. ((redisReply*)reply)->elements == 0);
  487. freeReplyObject(reply);
  488. redisReaderFree(reader);
  489. /* RESP3 verbatim strings (GitHub issue #802) */
  490. test("Can parse RESP3 verbatim strings: ");
  491. reader = redisReaderCreate();
  492. redisReaderFeed(reader,(char*)"=10\r\ntxt:LOLWUT\r\n",17);
  493. ret = redisReaderGetReply(reader,&reply);
  494. test_cond(ret == REDIS_OK &&
  495. ((redisReply*)reply)->type == REDIS_REPLY_VERB &&
  496. !memcmp(((redisReply*)reply)->str,"LOLWUT", 6));
  497. freeReplyObject(reply);
  498. redisReaderFree(reader);
  499. /* RESP3 push messages (Github issue #815) */
  500. test("Can parse RESP3 push messages: ");
  501. reader = redisReaderCreate();
  502. redisReaderFeed(reader,(char*)">2\r\n$6\r\nLOLWUT\r\n:42\r\n",21);
  503. ret = redisReaderGetReply(reader,&reply);
  504. test_cond(ret == REDIS_OK &&
  505. ((redisReply*)reply)->type == REDIS_REPLY_PUSH &&
  506. ((redisReply*)reply)->elements == 2 &&
  507. ((redisReply*)reply)->element[0]->type == REDIS_REPLY_STRING &&
  508. !memcmp(((redisReply*)reply)->element[0]->str,"LOLWUT",6) &&
  509. ((redisReply*)reply)->element[1]->type == REDIS_REPLY_INTEGER &&
  510. ((redisReply*)reply)->element[1]->integer == 42);
  511. freeReplyObject(reply);
  512. redisReaderFree(reader);
  513. }
  514. static void test_free_null(void) {
  515. void *redisCtx = NULL;
  516. void *reply = NULL;
  517. test("Don't fail when redisFree is passed a NULL value: ");
  518. redisFree(redisCtx);
  519. test_cond(redisCtx == NULL);
  520. test("Don't fail when freeReplyObject is passed a NULL value: ");
  521. freeReplyObject(reply);
  522. test_cond(reply == NULL);
  523. }
  524. static void *hi_malloc_fail(size_t size) {
  525. (void)size;
  526. return NULL;
  527. }
  528. static void *hi_calloc_fail(size_t nmemb, size_t size) {
  529. (void)nmemb;
  530. (void)size;
  531. return NULL;
  532. }
  533. static void *hi_realloc_fail(void *ptr, size_t size) {
  534. (void)ptr;
  535. (void)size;
  536. return NULL;
  537. }
  538. static void test_allocator_injection(void) {
  539. hiredisAllocFuncs ha = {
  540. .mallocFn = hi_malloc_fail,
  541. .callocFn = hi_calloc_fail,
  542. .reallocFn = hi_realloc_fail,
  543. .strdupFn = strdup,
  544. .freeFn = free,
  545. };
  546. // Override hiredis allocators
  547. hiredisSetAllocators(&ha);
  548. test("redisContext uses injected allocators: ");
  549. redisContext *c = redisConnect("localhost", 6379);
  550. test_cond(c == NULL);
  551. test("redisReader uses injected allocators: ");
  552. redisReader *reader = redisReaderCreate();
  553. test_cond(reader == NULL);
  554. // Return allocators to default
  555. hiredisResetAllocators();
  556. }
  557. #define HIREDIS_BAD_DOMAIN "idontexist-noreally.com"
  558. static void test_blocking_connection_errors(void) {
  559. redisContext *c;
  560. struct addrinfo hints = {.ai_family = AF_INET};
  561. struct addrinfo *ai_tmp = NULL;
  562. int rv = getaddrinfo(HIREDIS_BAD_DOMAIN, "6379", &hints, &ai_tmp);
  563. if (rv != 0) {
  564. // Address does *not* exist
  565. test("Returns error when host cannot be resolved: ");
  566. // First see if this domain name *actually* resolves to NXDOMAIN
  567. c = redisConnect(HIREDIS_BAD_DOMAIN, 6379);
  568. test_cond(
  569. c->err == REDIS_ERR_OTHER &&
  570. (strcmp(c->errstr, "Name or service not known") == 0 ||
  571. strcmp(c->errstr, "Can't resolve: " HIREDIS_BAD_DOMAIN) == 0 ||
  572. strcmp(c->errstr, "Name does not resolve") == 0 ||
  573. strcmp(c->errstr, "nodename nor servname provided, or not known") == 0 ||
  574. strcmp(c->errstr, "No address associated with hostname") == 0 ||
  575. strcmp(c->errstr, "Temporary failure in name resolution") == 0 ||
  576. strcmp(c->errstr, "hostname nor servname provided, or not known") == 0 ||
  577. strcmp(c->errstr, "no address associated with name") == 0 ||
  578. strcmp(c->errstr, "No such host is known. ") == 0));
  579. redisFree(c);
  580. } else {
  581. printf("Skipping NXDOMAIN test. Found evil ISP!\n");
  582. freeaddrinfo(ai_tmp);
  583. }
  584. #ifndef _WIN32
  585. test("Returns error when the port is not open: ");
  586. c = redisConnect((char*)"localhost", 1);
  587. test_cond(c->err == REDIS_ERR_IO &&
  588. strcmp(c->errstr,"Connection refused") == 0);
  589. redisFree(c);
  590. test("Returns error when the unix_sock socket path doesn't accept connections: ");
  591. c = redisConnectUnix((char*)"/tmp/idontexist.sock");
  592. test_cond(c->err == REDIS_ERR_IO); /* Don't care about the message... */
  593. redisFree(c);
  594. #endif
  595. }
  596. /* Test push handler */
  597. void push_handler(void *privdata, void *r) {
  598. struct pushCounters *pcounts = privdata;
  599. redisReply *reply = r, *payload;
  600. assert(reply && reply->type == REDIS_REPLY_PUSH && reply->elements == 2);
  601. payload = reply->element[1];
  602. if (payload->type == REDIS_REPLY_ARRAY) {
  603. payload = payload->element[0];
  604. }
  605. if (payload->type == REDIS_REPLY_STRING) {
  606. pcounts->str++;
  607. } else if (payload->type == REDIS_REPLY_NIL) {
  608. pcounts->nil++;
  609. }
  610. freeReplyObject(reply);
  611. }
  612. /* Dummy function just to test setting a callback with redisOptions */
  613. void push_handler_async(redisAsyncContext *ac, void *reply) {
  614. (void)ac;
  615. (void)reply;
  616. }
  617. static void test_resp3_push_handler(redisContext *c) {
  618. struct pushCounters pc = {0};
  619. redisPushFn *old = NULL;
  620. redisReply *reply;
  621. void *privdata;
  622. /* Switch to RESP3 and turn on client tracking */
  623. send_hello(c, 3);
  624. send_client_tracking(c, "ON");
  625. privdata = c->privdata;
  626. c->privdata = &pc;
  627. reply = redisCommand(c, "GET key:0");
  628. assert(reply != NULL);
  629. freeReplyObject(reply);
  630. test("RESP3 PUSH messages are handled out of band by default: ");
  631. reply = redisCommand(c, "SET key:0 val:0");
  632. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS);
  633. freeReplyObject(reply);
  634. assert((reply = redisCommand(c, "GET key:0")) != NULL);
  635. freeReplyObject(reply);
  636. old = redisSetPushCallback(c, push_handler);
  637. test("We can set a custom RESP3 PUSH handler: ");
  638. reply = redisCommand(c, "SET key:0 val:0");
  639. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && pc.str == 1);
  640. freeReplyObject(reply);
  641. test("We properly handle a NIL invalidation payload: ");
  642. reply = redisCommand(c, "FLUSHDB");
  643. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && pc.nil == 1);
  644. freeReplyObject(reply);
  645. /* Unset the push callback and generate an invalidate message making
  646. * sure it is not handled out of band. */
  647. test("With no handler, PUSH replies come in-band: ");
  648. redisSetPushCallback(c, NULL);
  649. assert((reply = redisCommand(c, "GET key:0")) != NULL);
  650. freeReplyObject(reply);
  651. assert((reply = redisCommand(c, "SET key:0 invalid")) != NULL);
  652. test_cond(reply->type == REDIS_REPLY_PUSH);
  653. freeReplyObject(reply);
  654. test("With no PUSH handler, no replies are lost: ");
  655. assert(redisGetReply(c, (void**)&reply) == REDIS_OK);
  656. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS);
  657. freeReplyObject(reply);
  658. /* Return to the originally set PUSH handler */
  659. assert(old != NULL);
  660. redisSetPushCallback(c, old);
  661. /* Switch back to RESP2 and disable tracking */
  662. c->privdata = privdata;
  663. send_client_tracking(c, "OFF");
  664. send_hello(c, 2);
  665. }
  666. redisOptions get_redis_tcp_options(struct config config) {
  667. redisOptions options = {0};
  668. REDIS_OPTIONS_SET_TCP(&options, config.tcp.host, config.tcp.port);
  669. return options;
  670. }
  671. static void test_resp3_push_options(struct config config) {
  672. redisAsyncContext *ac;
  673. redisContext *c;
  674. redisOptions options;
  675. test("We set a default RESP3 handler for redisContext: ");
  676. options = get_redis_tcp_options(config);
  677. assert((c = redisConnectWithOptions(&options)) != NULL);
  678. test_cond(c->push_cb != NULL);
  679. redisFree(c);
  680. test("We don't set a default RESP3 push handler for redisAsyncContext: ");
  681. options = get_redis_tcp_options(config);
  682. assert((ac = redisAsyncConnectWithOptions(&options)) != NULL);
  683. test_cond(ac->c.push_cb == NULL);
  684. redisAsyncFree(ac);
  685. test("Our REDIS_OPT_NO_PUSH_AUTOFREE flag works: ");
  686. options = get_redis_tcp_options(config);
  687. options.options |= REDIS_OPT_NO_PUSH_AUTOFREE;
  688. assert((c = redisConnectWithOptions(&options)) != NULL);
  689. test_cond(c->push_cb == NULL);
  690. redisFree(c);
  691. test("We can use redisOptions to set a custom PUSH handler for redisContext: ");
  692. options = get_redis_tcp_options(config);
  693. options.push_cb = push_handler;
  694. assert((c = redisConnectWithOptions(&options)) != NULL);
  695. test_cond(c->push_cb == push_handler);
  696. redisFree(c);
  697. test("We can use redisOptions to set a custom PUSH handler for redisAsyncContext: ");
  698. options = get_redis_tcp_options(config);
  699. options.async_push_cb = push_handler_async;
  700. assert((ac = redisAsyncConnectWithOptions(&options)) != NULL);
  701. test_cond(ac->push_cb == push_handler_async);
  702. redisAsyncFree(ac);
  703. }
  704. void free_privdata(void *privdata) {
  705. struct privdata *data = privdata;
  706. data->dtor_counter++;
  707. }
  708. static void test_privdata_hooks(struct config config) {
  709. struct privdata data = {0};
  710. redisOptions options;
  711. redisContext *c;
  712. test("We can use redisOptions to set privdata: ");
  713. options = get_redis_tcp_options(config);
  714. REDIS_OPTIONS_SET_PRIVDATA(&options, &data, free_privdata);
  715. assert((c = redisConnectWithOptions(&options)) != NULL);
  716. test_cond(c->privdata == &data);
  717. test("Our privdata destructor fires when we free the context: ");
  718. redisFree(c);
  719. test_cond(data.dtor_counter == 1);
  720. }
  721. static void test_blocking_connection(struct config config) {
  722. redisContext *c;
  723. redisReply *reply;
  724. int major;
  725. c = do_connect(config);
  726. test("Is able to deliver commands: ");
  727. reply = redisCommand(c,"PING");
  728. test_cond(reply->type == REDIS_REPLY_STATUS &&
  729. strcasecmp(reply->str,"pong") == 0)
  730. freeReplyObject(reply);
  731. test("Is a able to send commands verbatim: ");
  732. reply = redisCommand(c,"SET foo bar");
  733. test_cond (reply->type == REDIS_REPLY_STATUS &&
  734. strcasecmp(reply->str,"ok") == 0)
  735. freeReplyObject(reply);
  736. test("%%s String interpolation works: ");
  737. reply = redisCommand(c,"SET %s %s","foo","hello world");
  738. freeReplyObject(reply);
  739. reply = redisCommand(c,"GET foo");
  740. test_cond(reply->type == REDIS_REPLY_STRING &&
  741. strcmp(reply->str,"hello world") == 0);
  742. freeReplyObject(reply);
  743. test("%%b String interpolation works: ");
  744. reply = redisCommand(c,"SET %b %b","foo",(size_t)3,"hello\x00world",(size_t)11);
  745. freeReplyObject(reply);
  746. reply = redisCommand(c,"GET foo");
  747. test_cond(reply->type == REDIS_REPLY_STRING &&
  748. memcmp(reply->str,"hello\x00world",11) == 0)
  749. test("Binary reply length is correct: ");
  750. test_cond(reply->len == 11)
  751. freeReplyObject(reply);
  752. test("Can parse nil replies: ");
  753. reply = redisCommand(c,"GET nokey");
  754. test_cond(reply->type == REDIS_REPLY_NIL)
  755. freeReplyObject(reply);
  756. /* test 7 */
  757. test("Can parse integer replies: ");
  758. reply = redisCommand(c,"INCR mycounter");
  759. test_cond(reply->type == REDIS_REPLY_INTEGER && reply->integer == 1)
  760. freeReplyObject(reply);
  761. test("Can parse multi bulk replies: ");
  762. freeReplyObject(redisCommand(c,"LPUSH mylist foo"));
  763. freeReplyObject(redisCommand(c,"LPUSH mylist bar"));
  764. reply = redisCommand(c,"LRANGE mylist 0 -1");
  765. test_cond(reply->type == REDIS_REPLY_ARRAY &&
  766. reply->elements == 2 &&
  767. !memcmp(reply->element[0]->str,"bar",3) &&
  768. !memcmp(reply->element[1]->str,"foo",3))
  769. freeReplyObject(reply);
  770. /* m/e with multi bulk reply *before* other reply.
  771. * specifically test ordering of reply items to parse. */
  772. test("Can handle nested multi bulk replies: ");
  773. freeReplyObject(redisCommand(c,"MULTI"));
  774. freeReplyObject(redisCommand(c,"LRANGE mylist 0 -1"));
  775. freeReplyObject(redisCommand(c,"PING"));
  776. reply = (redisCommand(c,"EXEC"));
  777. test_cond(reply->type == REDIS_REPLY_ARRAY &&
  778. reply->elements == 2 &&
  779. reply->element[0]->type == REDIS_REPLY_ARRAY &&
  780. reply->element[0]->elements == 2 &&
  781. !memcmp(reply->element[0]->element[0]->str,"bar",3) &&
  782. !memcmp(reply->element[0]->element[1]->str,"foo",3) &&
  783. reply->element[1]->type == REDIS_REPLY_STATUS &&
  784. strcasecmp(reply->element[1]->str,"pong") == 0);
  785. freeReplyObject(reply);
  786. /* Make sure passing NULL to redisGetReply is safe */
  787. test("Can pass NULL to redisGetReply: ");
  788. assert(redisAppendCommand(c, "PING") == REDIS_OK);
  789. test_cond(redisGetReply(c, NULL) == REDIS_OK);
  790. get_redis_version(c, &major, NULL);
  791. if (major >= 6) test_resp3_push_handler(c);
  792. test_resp3_push_options(config);
  793. test_privdata_hooks(config);
  794. disconnect(c, 0);
  795. }
  796. /* Send DEBUG SLEEP 0 to detect if we have this command */
  797. static int detect_debug_sleep(redisContext *c) {
  798. int detected;
  799. redisReply *reply = redisCommand(c, "DEBUG SLEEP 0\r\n");
  800. if (reply == NULL || c->err) {
  801. const char *cause = c->err ? c->errstr : "(none)";
  802. fprintf(stderr, "Error testing for DEBUG SLEEP (Redis error: %s), exiting\n", cause);
  803. exit(-1);
  804. }
  805. detected = reply->type == REDIS_REPLY_STATUS;
  806. freeReplyObject(reply);
  807. return detected;
  808. }
  809. static void test_blocking_connection_timeouts(struct config config) {
  810. redisContext *c;
  811. redisReply *reply;
  812. ssize_t s;
  813. const char *sleep_cmd = "DEBUG SLEEP 3\r\n";
  814. struct timeval tv;
  815. c = do_connect(config);
  816. test("Successfully completes a command when the timeout is not exceeded: ");
  817. reply = redisCommand(c,"SET foo fast");
  818. freeReplyObject(reply);
  819. tv.tv_sec = 0;
  820. tv.tv_usec = 10000;
  821. redisSetTimeout(c, tv);
  822. reply = redisCommand(c, "GET foo");
  823. test_cond(reply != NULL && reply->type == REDIS_REPLY_STRING && memcmp(reply->str, "fast", 4) == 0);
  824. freeReplyObject(reply);
  825. disconnect(c, 0);
  826. c = do_connect(config);
  827. test("Does not return a reply when the command times out: ");
  828. if (detect_debug_sleep(c)) {
  829. redisAppendFormattedCommand(c, sleep_cmd, strlen(sleep_cmd));
  830. s = c->funcs->write(c);
  831. tv.tv_sec = 0;
  832. tv.tv_usec = 10000;
  833. redisSetTimeout(c, tv);
  834. reply = redisCommand(c, "GET foo");
  835. #ifndef _WIN32
  836. test_cond(s > 0 && reply == NULL && c->err == REDIS_ERR_IO &&
  837. strcmp(c->errstr, "Resource temporarily unavailable") == 0);
  838. #else
  839. test_cond(s > 0 && reply == NULL && c->err == REDIS_ERR_TIMEOUT &&
  840. strcmp(c->errstr, "recv timeout") == 0);
  841. #endif
  842. freeReplyObject(reply);
  843. } else {
  844. test_skipped();
  845. }
  846. test("Reconnect properly reconnects after a timeout: ");
  847. do_reconnect(c, config);
  848. reply = redisCommand(c, "PING");
  849. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "PONG") == 0);
  850. freeReplyObject(reply);
  851. test("Reconnect properly uses owned parameters: ");
  852. config.tcp.host = "foo";
  853. config.unix_sock.path = "foo";
  854. do_reconnect(c, config);
  855. reply = redisCommand(c, "PING");
  856. test_cond(reply != NULL && reply->type == REDIS_REPLY_STATUS && strcmp(reply->str, "PONG") == 0);
  857. freeReplyObject(reply);
  858. disconnect(c, 0);
  859. }
  860. static void test_blocking_io_errors(struct config config) {
  861. redisContext *c;
  862. redisReply *reply;
  863. void *_reply;
  864. int major, minor;
  865. /* Connect to target given by config. */
  866. c = do_connect(config);
  867. get_redis_version(c, &major, &minor);
  868. test("Returns I/O error when the connection is lost: ");
  869. reply = redisCommand(c,"QUIT");
  870. if (major > 2 || (major == 2 && minor > 0)) {
  871. /* > 2.0 returns OK on QUIT and read() should be issued once more
  872. * to know the descriptor is at EOF. */
  873. test_cond(strcasecmp(reply->str,"OK") == 0 &&
  874. redisGetReply(c,&_reply) == REDIS_ERR);
  875. freeReplyObject(reply);
  876. } else {
  877. test_cond(reply == NULL);
  878. }
  879. #ifndef _WIN32
  880. /* On 2.0, QUIT will cause the connection to be closed immediately and
  881. * the read(2) for the reply on QUIT will set the error to EOF.
  882. * On >2.0, QUIT will return with OK and another read(2) needed to be
  883. * issued to find out the socket was closed by the server. In both
  884. * conditions, the error will be set to EOF. */
  885. assert(c->err == REDIS_ERR_EOF &&
  886. strcmp(c->errstr,"Server closed the connection") == 0);
  887. #endif
  888. redisFree(c);
  889. c = do_connect(config);
  890. test("Returns I/O error on socket timeout: ");
  891. struct timeval tv = { 0, 1000 };
  892. assert(redisSetTimeout(c,tv) == REDIS_OK);
  893. int respcode = redisGetReply(c,&_reply);
  894. #ifndef _WIN32
  895. test_cond(respcode == REDIS_ERR && c->err == REDIS_ERR_IO && errno == EAGAIN);
  896. #else
  897. test_cond(respcode == REDIS_ERR && c->err == REDIS_ERR_TIMEOUT);
  898. #endif
  899. redisFree(c);
  900. }
  901. static void test_invalid_timeout_errors(struct config config) {
  902. redisContext *c;
  903. test("Set error when an invalid timeout usec value is given to redisConnectWithTimeout: ");
  904. config.tcp.timeout.tv_sec = 0;
  905. config.tcp.timeout.tv_usec = 10000001;
  906. c = redisConnectWithTimeout(config.tcp.host, config.tcp.port, config.tcp.timeout);
  907. test_cond(c->err == REDIS_ERR_IO && strcmp(c->errstr, "Invalid timeout specified") == 0);
  908. redisFree(c);
  909. test("Set error when an invalid timeout sec value is given to redisConnectWithTimeout: ");
  910. config.tcp.timeout.tv_sec = (((LONG_MAX) - 999) / 1000) + 1;
  911. config.tcp.timeout.tv_usec = 0;
  912. c = redisConnectWithTimeout(config.tcp.host, config.tcp.port, config.tcp.timeout);
  913. test_cond(c->err == REDIS_ERR_IO && strcmp(c->errstr, "Invalid timeout specified") == 0);
  914. redisFree(c);
  915. }
  916. /* Wrap malloc to abort on failure so OOM checks don't make the test logic
  917. * harder to follow. */
  918. void *hi_malloc_safe(size_t size) {
  919. void *ptr = hi_malloc(size);
  920. if (ptr == NULL) {
  921. fprintf(stderr, "Error: Out of memory\n");
  922. exit(-1);
  923. }
  924. return ptr;
  925. }
  926. static void test_throughput(struct config config) {
  927. redisContext *c = do_connect(config);
  928. redisReply **replies;
  929. int i, num;
  930. long long t1, t2;
  931. test("Throughput:\n");
  932. for (i = 0; i < 500; i++)
  933. freeReplyObject(redisCommand(c,"LPUSH mylist foo"));
  934. num = 1000;
  935. replies = hi_malloc_safe(sizeof(redisReply*)*num);
  936. t1 = usec();
  937. for (i = 0; i < num; i++) {
  938. replies[i] = redisCommand(c,"PING");
  939. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS);
  940. }
  941. t2 = usec();
  942. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  943. hi_free(replies);
  944. printf("\t(%dx PING: %.3fs)\n", num, (t2-t1)/1000000.0);
  945. replies = hi_malloc_safe(sizeof(redisReply*)*num);
  946. t1 = usec();
  947. for (i = 0; i < num; i++) {
  948. replies[i] = redisCommand(c,"LRANGE mylist 0 499");
  949. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY);
  950. assert(replies[i] != NULL && replies[i]->elements == 500);
  951. }
  952. t2 = usec();
  953. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  954. hi_free(replies);
  955. printf("\t(%dx LRANGE with 500 elements: %.3fs)\n", num, (t2-t1)/1000000.0);
  956. replies = hi_malloc_safe(sizeof(redisReply*)*num);
  957. t1 = usec();
  958. for (i = 0; i < num; i++) {
  959. replies[i] = redisCommand(c, "INCRBY incrkey %d", 1000000);
  960. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_INTEGER);
  961. }
  962. t2 = usec();
  963. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  964. hi_free(replies);
  965. printf("\t(%dx INCRBY: %.3fs)\n", num, (t2-t1)/1000000.0);
  966. num = 10000;
  967. replies = hi_malloc_safe(sizeof(redisReply*)*num);
  968. for (i = 0; i < num; i++)
  969. redisAppendCommand(c,"PING");
  970. t1 = usec();
  971. for (i = 0; i < num; i++) {
  972. assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
  973. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_STATUS);
  974. }
  975. t2 = usec();
  976. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  977. hi_free(replies);
  978. printf("\t(%dx PING (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
  979. replies = hi_malloc_safe(sizeof(redisReply*)*num);
  980. for (i = 0; i < num; i++)
  981. redisAppendCommand(c,"LRANGE mylist 0 499");
  982. t1 = usec();
  983. for (i = 0; i < num; i++) {
  984. assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
  985. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_ARRAY);
  986. assert(replies[i] != NULL && replies[i]->elements == 500);
  987. }
  988. t2 = usec();
  989. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  990. hi_free(replies);
  991. printf("\t(%dx LRANGE with 500 elements (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
  992. replies = hi_malloc_safe(sizeof(redisReply*)*num);
  993. for (i = 0; i < num; i++)
  994. redisAppendCommand(c,"INCRBY incrkey %d", 1000000);
  995. t1 = usec();
  996. for (i = 0; i < num; i++) {
  997. assert(redisGetReply(c, (void*)&replies[i]) == REDIS_OK);
  998. assert(replies[i] != NULL && replies[i]->type == REDIS_REPLY_INTEGER);
  999. }
  1000. t2 = usec();
  1001. for (i = 0; i < num; i++) freeReplyObject(replies[i]);
  1002. hi_free(replies);
  1003. printf("\t(%dx INCRBY (pipelined): %.3fs)\n", num, (t2-t1)/1000000.0);
  1004. disconnect(c, 0);
  1005. }
  1006. // static long __test_callback_flags = 0;
  1007. // static void __test_callback(redisContext *c, void *privdata) {
  1008. // ((void)c);
  1009. // /* Shift to detect execution order */
  1010. // __test_callback_flags <<= 8;
  1011. // __test_callback_flags |= (long)privdata;
  1012. // }
  1013. //
  1014. // static void __test_reply_callback(redisContext *c, redisReply *reply, void *privdata) {
  1015. // ((void)c);
  1016. // /* Shift to detect execution order */
  1017. // __test_callback_flags <<= 8;
  1018. // __test_callback_flags |= (long)privdata;
  1019. // if (reply) freeReplyObject(reply);
  1020. // }
  1021. //
  1022. // static redisContext *__connect_nonblock() {
  1023. // /* Reset callback flags */
  1024. // __test_callback_flags = 0;
  1025. // return redisConnectNonBlock("127.0.0.1", port, NULL);
  1026. // }
  1027. //
  1028. // static void test_nonblocking_connection() {
  1029. // redisContext *c;
  1030. // int wdone = 0;
  1031. //
  1032. // test("Calls command callback when command is issued: ");
  1033. // c = __connect_nonblock();
  1034. // redisSetCommandCallback(c,__test_callback,(void*)1);
  1035. // redisCommand(c,"PING");
  1036. // test_cond(__test_callback_flags == 1);
  1037. // redisFree(c);
  1038. //
  1039. // test("Calls disconnect callback on redisDisconnect: ");
  1040. // c = __connect_nonblock();
  1041. // redisSetDisconnectCallback(c,__test_callback,(void*)2);
  1042. // redisDisconnect(c);
  1043. // test_cond(__test_callback_flags == 2);
  1044. // redisFree(c);
  1045. //
  1046. // test("Calls disconnect callback and free callback on redisFree: ");
  1047. // c = __connect_nonblock();
  1048. // redisSetDisconnectCallback(c,__test_callback,(void*)2);
  1049. // redisSetFreeCallback(c,__test_callback,(void*)4);
  1050. // redisFree(c);
  1051. // test_cond(__test_callback_flags == ((2 << 8) | 4));
  1052. //
  1053. // test("redisBufferWrite against empty write buffer: ");
  1054. // c = __connect_nonblock();
  1055. // test_cond(redisBufferWrite(c,&wdone) == REDIS_OK && wdone == 1);
  1056. // redisFree(c);
  1057. //
  1058. // test("redisBufferWrite against not yet connected fd: ");
  1059. // c = __connect_nonblock();
  1060. // redisCommand(c,"PING");
  1061. // test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
  1062. // strncmp(c->error,"write:",6) == 0);
  1063. // redisFree(c);
  1064. //
  1065. // test("redisBufferWrite against closed fd: ");
  1066. // c = __connect_nonblock();
  1067. // redisCommand(c,"PING");
  1068. // redisDisconnect(c);
  1069. // test_cond(redisBufferWrite(c,NULL) == REDIS_ERR &&
  1070. // strncmp(c->error,"write:",6) == 0);
  1071. // redisFree(c);
  1072. //
  1073. // test("Process callbacks in the right sequence: ");
  1074. // c = __connect_nonblock();
  1075. // redisCommandWithCallback(c,__test_reply_callback,(void*)1,"PING");
  1076. // redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
  1077. // redisCommandWithCallback(c,__test_reply_callback,(void*)3,"PING");
  1078. //
  1079. // /* Write output buffer */
  1080. // wdone = 0;
  1081. // while(!wdone) {
  1082. // usleep(500);
  1083. // redisBufferWrite(c,&wdone);
  1084. // }
  1085. //
  1086. // /* Read until at least one callback is executed (the 3 replies will
  1087. // * arrive in a single packet, causing all callbacks to be executed in
  1088. // * a single pass). */
  1089. // while(__test_callback_flags == 0) {
  1090. // assert(redisBufferRead(c) == REDIS_OK);
  1091. // redisProcessCallbacks(c);
  1092. // }
  1093. // test_cond(__test_callback_flags == 0x010203);
  1094. // redisFree(c);
  1095. //
  1096. // test("redisDisconnect executes pending callbacks with NULL reply: ");
  1097. // c = __connect_nonblock();
  1098. // redisSetDisconnectCallback(c,__test_callback,(void*)1);
  1099. // redisCommandWithCallback(c,__test_reply_callback,(void*)2,"PING");
  1100. // redisDisconnect(c);
  1101. // test_cond(__test_callback_flags == 0x0201);
  1102. // redisFree(c);
  1103. // }
  1104. int main(int argc, char **argv) {
  1105. struct config cfg = {
  1106. .tcp = {
  1107. .host = "127.0.0.1",
  1108. .port = 6379
  1109. },
  1110. .unix_sock = {
  1111. .path = "/tmp/redis.sock"
  1112. }
  1113. };
  1114. int throughput = 1;
  1115. int test_inherit_fd = 1;
  1116. int skips_as_fails = 0;
  1117. int test_unix_socket;
  1118. /* Parse command line options. */
  1119. argv++; argc--;
  1120. while (argc) {
  1121. if (argc >= 2 && !strcmp(argv[0],"-h")) {
  1122. argv++; argc--;
  1123. cfg.tcp.host = argv[0];
  1124. } else if (argc >= 2 && !strcmp(argv[0],"-p")) {
  1125. argv++; argc--;
  1126. cfg.tcp.port = atoi(argv[0]);
  1127. } else if (argc >= 2 && !strcmp(argv[0],"-s")) {
  1128. argv++; argc--;
  1129. cfg.unix_sock.path = argv[0];
  1130. } else if (argc >= 1 && !strcmp(argv[0],"--skip-throughput")) {
  1131. throughput = 0;
  1132. } else if (argc >= 1 && !strcmp(argv[0],"--skip-inherit-fd")) {
  1133. test_inherit_fd = 0;
  1134. } else if (argc >= 1 && !strcmp(argv[0],"--skips-as-fails")) {
  1135. skips_as_fails = 1;
  1136. #ifdef HIREDIS_TEST_SSL
  1137. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-port")) {
  1138. argv++; argc--;
  1139. cfg.ssl.port = atoi(argv[0]);
  1140. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-host")) {
  1141. argv++; argc--;
  1142. cfg.ssl.host = argv[0];
  1143. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-ca-cert")) {
  1144. argv++; argc--;
  1145. cfg.ssl.ca_cert = argv[0];
  1146. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-cert")) {
  1147. argv++; argc--;
  1148. cfg.ssl.cert = argv[0];
  1149. } else if (argc >= 2 && !strcmp(argv[0],"--ssl-key")) {
  1150. argv++; argc--;
  1151. cfg.ssl.key = argv[0];
  1152. #endif
  1153. } else {
  1154. fprintf(stderr, "Invalid argument: %s\n", argv[0]);
  1155. exit(1);
  1156. }
  1157. argv++; argc--;
  1158. }
  1159. #ifndef _WIN32
  1160. /* Ignore broken pipe signal (for I/O error tests). */
  1161. signal(SIGPIPE, SIG_IGN);
  1162. test_unix_socket = access(cfg.unix_sock.path, F_OK) == 0;
  1163. #else
  1164. /* Unix sockets don't exist in Windows */
  1165. test_unix_socket = 0;
  1166. #endif
  1167. test_allocator_injection();
  1168. test_format_commands();
  1169. test_reply_reader();
  1170. test_blocking_connection_errors();
  1171. test_free_null();
  1172. printf("\nTesting against TCP connection (%s:%d):\n", cfg.tcp.host, cfg.tcp.port);
  1173. cfg.type = CONN_TCP;
  1174. test_blocking_connection(cfg);
  1175. test_blocking_connection_timeouts(cfg);
  1176. test_blocking_io_errors(cfg);
  1177. test_invalid_timeout_errors(cfg);
  1178. test_append_formatted_commands(cfg);
  1179. if (throughput) test_throughput(cfg);
  1180. printf("\nTesting against Unix socket connection (%s): ", cfg.unix_sock.path);
  1181. if (test_unix_socket) {
  1182. printf("\n");
  1183. cfg.type = CONN_UNIX;
  1184. test_blocking_connection(cfg);
  1185. test_blocking_connection_timeouts(cfg);
  1186. test_blocking_io_errors(cfg);
  1187. if (throughput) test_throughput(cfg);
  1188. } else {
  1189. test_skipped();
  1190. }
  1191. #ifdef HIREDIS_TEST_SSL
  1192. if (cfg.ssl.port && cfg.ssl.host) {
  1193. redisInitOpenSSL();
  1194. _ssl_ctx = redisCreateSSLContext(cfg.ssl.ca_cert, NULL, cfg.ssl.cert, cfg.ssl.key, NULL, NULL);
  1195. assert(_ssl_ctx != NULL);
  1196. printf("\nTesting against SSL connection (%s:%d):\n", cfg.ssl.host, cfg.ssl.port);
  1197. cfg.type = CONN_SSL;
  1198. test_blocking_connection(cfg);
  1199. test_blocking_connection_timeouts(cfg);
  1200. test_blocking_io_errors(cfg);
  1201. test_invalid_timeout_errors(cfg);
  1202. test_append_formatted_commands(cfg);
  1203. if (throughput) test_throughput(cfg);
  1204. redisFreeSSLContext(_ssl_ctx);
  1205. _ssl_ctx = NULL;
  1206. }
  1207. #endif
  1208. if (test_inherit_fd) {
  1209. printf("\nTesting against inherited fd (%s): ", cfg.unix_sock.path);
  1210. if (test_unix_socket) {
  1211. printf("\n");
  1212. cfg.type = CONN_FD;
  1213. test_blocking_connection(cfg);
  1214. } else {
  1215. test_skipped();
  1216. }
  1217. }
  1218. if (fails || (skips_as_fails && skips)) {
  1219. printf("*** %d TESTS FAILED ***\n", fails);
  1220. if (skips) {
  1221. printf("*** %d TESTS SKIPPED ***\n", skips);
  1222. }
  1223. return 1;
  1224. }
  1225. printf("ALL TESTS PASSED (%d skipped)\n", skips);
  1226. return 0;
  1227. }