xref: /redis-3.2.3/src/redis-cli.c (revision 8a09e129)
1 /* Redis CLI (command line interface)
2  *
3  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  *   * Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  *   * Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *   * Neither the name of Redis nor the names of its contributors may be used
15  *     to endorse or promote products derived from this software without
16  *     specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include "fmacros.h"
32 #include "version.h"
33 
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <signal.h>
38 #include <unistd.h>
39 #include <time.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <assert.h>
45 #include <fcntl.h>
46 #include <limits.h>
47 
48 #include "hiredis.h"
49 #include "sds.h"
50 #include "zmalloc.h"
51 #include "linenoise.h"
52 #include "help.h"
53 #include "anet.h"
54 #include "ae.h"
55 
56 #define REDIS_NOTUSED(V) ((void) V)
57 
58 #define OUTPUT_STANDARD 0
59 #define OUTPUT_RAW 1
60 #define OUTPUT_CSV 2
61 #define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */
62 #define REDIS_CLI_DEFAULT_PIPE_TIMEOUT 30 /* seconds */
63 
64 static redisContext *context;
65 static struct config {
66     char *hostip;
67     int hostport;
68     char *hostsocket;
69     long repeat;
70     long interval;
71     int dbnum;
72     int interactive;
73     int shutdown;
74     int monitor_mode;
75     int pubsub_mode;
76     int latency_mode;
77     int latency_history;
78     int cluster_mode;
79     int cluster_reissue_command;
80     int slave_mode;
81     int pipe_mode;
82     int pipe_timeout;
83     int getrdb_mode;
84     int stat_mode;
85     int scan_mode;
86     int intrinsic_latency_mode;
87     int intrinsic_latency_duration;
88     char *pattern;
89     char *rdb_filename;
90     int bigkeys;
91     int stdinarg; /* get last arg from stdin. (-x option) */
92     char *auth;
93     int output; /* output mode, see OUTPUT_* defines */
94     sds mb_delim;
95     char prompt[128];
96     char *eval;
97     int last_cmd_type;
98 } config;
99 
100 static volatile sig_atomic_t force_cancel_loop = 0;
101 static void usage(void);
102 static void slaveMode(void);
103 char *redisGitSHA1(void);
104 char *redisGitDirty(void);
105 
106 /*------------------------------------------------------------------------------
107  * Utility functions
108  *--------------------------------------------------------------------------- */
109 
110 static long long ustime(void) {
111     struct timeval tv;
112     long long ust;
113 
114     gettimeofday(&tv, NULL);
115     ust = ((long long)tv.tv_sec)*1000000;
116     ust += tv.tv_usec;
117     return ust;
118 }
119 
120 static long long mstime(void) {
121     return ustime()/1000;
122 }
123 
124 static void cliRefreshPrompt(void) {
125     int len;
126 
127     if (config.hostsocket != NULL)
128         len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
129                        config.hostsocket);
130     else
131         len = snprintf(config.prompt,sizeof(config.prompt),
132                        strchr(config.hostip,':') ? "[%s]:%d" : "%s:%d",
133                        config.hostip, config.hostport);
134     /* Add [dbnum] if needed */
135     if (config.dbnum != 0 && config.last_cmd_type != REDIS_REPLY_ERROR)
136         len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
137             config.dbnum);
138     snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
139 }
140 
141 /*------------------------------------------------------------------------------
142  * Help functions
143  *--------------------------------------------------------------------------- */
144 
145 #define CLI_HELP_COMMAND 1
146 #define CLI_HELP_GROUP 2
147 
148 typedef struct {
149     int type;
150     int argc;
151     sds *argv;
152     sds full;
153 
154     /* Only used for help on commands */
155     struct commandHelp *org;
156 } helpEntry;
157 
158 static helpEntry *helpEntries;
159 static int helpEntriesLen;
160 
161 static sds cliVersion(void) {
162     sds version;
163     version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
164 
165     /* Add git commit and working tree status when available */
166     if (strtoll(redisGitSHA1(),NULL,16)) {
167         version = sdscatprintf(version, " (git:%s", redisGitSHA1());
168         if (strtoll(redisGitDirty(),NULL,10))
169             version = sdscatprintf(version, "-dirty");
170         version = sdscat(version, ")");
171     }
172     return version;
173 }
174 
175 static void cliInitHelp(void) {
176     int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
177     int groupslen = sizeof(commandGroups)/sizeof(char*);
178     int i, len, pos = 0;
179     helpEntry tmp;
180 
181     helpEntriesLen = len = commandslen+groupslen;
182     helpEntries = malloc(sizeof(helpEntry)*len);
183 
184     for (i = 0; i < groupslen; i++) {
185         tmp.argc = 1;
186         tmp.argv = malloc(sizeof(sds));
187         tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
188         tmp.full = tmp.argv[0];
189         tmp.type = CLI_HELP_GROUP;
190         tmp.org = NULL;
191         helpEntries[pos++] = tmp;
192     }
193 
194     for (i = 0; i < commandslen; i++) {
195         tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
196         tmp.full = sdsnew(commandHelp[i].name);
197         tmp.type = CLI_HELP_COMMAND;
198         tmp.org = &commandHelp[i];
199         helpEntries[pos++] = tmp;
200     }
201 }
202 
203 /* Output command help to stdout. */
204 static void cliOutputCommandHelp(struct commandHelp *help, int group) {
205     printf("\r\n  \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
206     printf("  \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
207     printf("  \x1b[33msince:\x1b[0m %s\r\n", help->since);
208     if (group) {
209         printf("  \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
210     }
211 }
212 
213 /* Print generic help. */
214 static void cliOutputGenericHelp(void) {
215     sds version = cliVersion();
216     printf(
217         "redis-cli %s\r\n"
218         "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
219         "      \"help <command>\" for help on <command>\r\n"
220         "      \"help <tab>\" to get a list of possible help topics\r\n"
221         "      \"quit\" to exit\r\n",
222         version
223     );
224     sdsfree(version);
225 }
226 
227 /* Output all command help, filtering by group or command name. */
228 static void cliOutputHelp(int argc, char **argv) {
229     int i, j, len;
230     int group = -1;
231     helpEntry *entry;
232     struct commandHelp *help;
233 
234     if (argc == 0) {
235         cliOutputGenericHelp();
236         return;
237     } else if (argc > 0 && argv[0][0] == '@') {
238         len = sizeof(commandGroups)/sizeof(char*);
239         for (i = 0; i < len; i++) {
240             if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
241                 group = i;
242                 break;
243             }
244         }
245     }
246 
247     assert(argc > 0);
248     for (i = 0; i < helpEntriesLen; i++) {
249         entry = &helpEntries[i];
250         if (entry->type != CLI_HELP_COMMAND) continue;
251 
252         help = entry->org;
253         if (group == -1) {
254             /* Compare all arguments */
255             if (argc == entry->argc) {
256                 for (j = 0; j < argc; j++) {
257                     if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
258                 }
259                 if (j == argc) {
260                     cliOutputCommandHelp(help,1);
261                 }
262             }
263         } else {
264             if (group == help->group) {
265                 cliOutputCommandHelp(help,0);
266             }
267         }
268     }
269     printf("\r\n");
270 }
271 
272 static void completionCallback(const char *buf, linenoiseCompletions *lc) {
273     size_t startpos = 0;
274     int mask;
275     int i;
276     size_t matchlen;
277     sds tmp;
278 
279     if (strncasecmp(buf,"help ",5) == 0) {
280         startpos = 5;
281         while (isspace(buf[startpos])) startpos++;
282         mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
283     } else {
284         mask = CLI_HELP_COMMAND;
285     }
286 
287     for (i = 0; i < helpEntriesLen; i++) {
288         if (!(helpEntries[i].type & mask)) continue;
289 
290         matchlen = strlen(buf+startpos);
291         if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
292             tmp = sdsnewlen(buf,startpos);
293             tmp = sdscat(tmp,helpEntries[i].full);
294             linenoiseAddCompletion(lc,tmp);
295             sdsfree(tmp);
296         }
297     }
298 }
299 
300 /*------------------------------------------------------------------------------
301  * Networking / parsing
302  *--------------------------------------------------------------------------- */
303 
304 /* Send AUTH command to the server */
305 static int cliAuth() {
306     redisReply *reply;
307     if (config.auth == NULL) return REDIS_OK;
308 
309     reply = redisCommand(context,"AUTH %s",config.auth);
310     if (reply != NULL) {
311         freeReplyObject(reply);
312         return REDIS_OK;
313     }
314     return REDIS_ERR;
315 }
316 
317 /* Send SELECT dbnum to the server */
318 static int cliSelect() {
319     redisReply *reply;
320     if (config.dbnum == 0) return REDIS_OK;
321 
322     reply = redisCommand(context,"SELECT %d",config.dbnum);
323     if (reply != NULL) {
324         int result = REDIS_OK;
325         if (reply->type == REDIS_REPLY_ERROR) result = REDIS_ERR;
326         freeReplyObject(reply);
327         return result;
328     }
329     return REDIS_ERR;
330 }
331 
332 /* Connect to the server. If force is not zero the connection is performed
333  * even if there is already a connected socket. */
334 static int cliConnect(int force) {
335     if (context == NULL || force) {
336         if (context != NULL)
337             redisFree(context);
338 
339         if (config.hostsocket == NULL) {
340             context = redisConnect(config.hostip,config.hostport);
341         } else {
342             context = redisConnectUnix(config.hostsocket);
343         }
344 
345         if (context->err) {
346             fprintf(stderr,"Could not connect to Redis at ");
347             if (config.hostsocket == NULL)
348                 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
349             else
350                 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
351             redisFree(context);
352             context = NULL;
353             return REDIS_ERR;
354         }
355 
356         /* Set aggressive KEEP_ALIVE socket option in the Redis context socket
357          * in order to prevent timeouts caused by the execution of long
358          * commands. At the same time this improves the detection of real
359          * errors. */
360         anetKeepAlive(NULL, context->fd, REDIS_CLI_KEEPALIVE_INTERVAL);
361 
362         /* Do AUTH and select the right DB. */
363         if (cliAuth() != REDIS_OK)
364             return REDIS_ERR;
365         if (cliSelect() != REDIS_OK)
366             return REDIS_ERR;
367     }
368     return REDIS_OK;
369 }
370 
371 static void cliPrintContextError(void) {
372     if (context == NULL) return;
373     fprintf(stderr,"Error: %s\n",context->errstr);
374 }
375 
376 static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
377     sds out = sdsempty();
378     switch (r->type) {
379     case REDIS_REPLY_ERROR:
380         out = sdscatprintf(out,"(error) %s\n", r->str);
381     break;
382     case REDIS_REPLY_STATUS:
383         out = sdscat(out,r->str);
384         out = sdscat(out,"\n");
385     break;
386     case REDIS_REPLY_INTEGER:
387         out = sdscatprintf(out,"(integer) %lld\n",r->integer);
388     break;
389     case REDIS_REPLY_STRING:
390         /* If you are producing output for the standard output we want
391         * a more interesting output with quoted characters and so forth */
392         out = sdscatrepr(out,r->str,r->len);
393         out = sdscat(out,"\n");
394     break;
395     case REDIS_REPLY_NIL:
396         out = sdscat(out,"(nil)\n");
397     break;
398     case REDIS_REPLY_ARRAY:
399         if (r->elements == 0) {
400             out = sdscat(out,"(empty list or set)\n");
401         } else {
402             unsigned int i, idxlen = 0;
403             char _prefixlen[16];
404             char _prefixfmt[16];
405             sds _prefix;
406             sds tmp;
407 
408             /* Calculate chars needed to represent the largest index */
409             i = r->elements;
410             do {
411                 idxlen++;
412                 i /= 10;
413             } while(i);
414 
415             /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
416             memset(_prefixlen,' ',idxlen+2);
417             _prefixlen[idxlen+2] = '\0';
418             _prefix = sdscat(sdsnew(prefix),_prefixlen);
419 
420             /* Setup prefix format for every entry */
421             snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
422 
423             for (i = 0; i < r->elements; i++) {
424                 /* Don't use the prefix for the first element, as the parent
425                  * caller already prepended the index number. */
426                 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
427 
428                 /* Format the multi bulk entry */
429                 tmp = cliFormatReplyTTY(r->element[i],_prefix);
430                 out = sdscatlen(out,tmp,sdslen(tmp));
431                 sdsfree(tmp);
432             }
433             sdsfree(_prefix);
434         }
435     break;
436     default:
437         fprintf(stderr,"Unknown reply type: %d\n", r->type);
438         exit(1);
439     }
440     return out;
441 }
442 
443 static sds cliFormatReplyRaw(redisReply *r) {
444     sds out = sdsempty(), tmp;
445     size_t i;
446 
447     switch (r->type) {
448     case REDIS_REPLY_NIL:
449         /* Nothing... */
450         break;
451     case REDIS_REPLY_ERROR:
452         out = sdscatlen(out,r->str,r->len);
453         out = sdscatlen(out,"\n",1);
454         break;
455     case REDIS_REPLY_STATUS:
456     case REDIS_REPLY_STRING:
457         out = sdscatlen(out,r->str,r->len);
458         break;
459     case REDIS_REPLY_INTEGER:
460         out = sdscatprintf(out,"%lld",r->integer);
461         break;
462     case REDIS_REPLY_ARRAY:
463         for (i = 0; i < r->elements; i++) {
464             if (i > 0) out = sdscat(out,config.mb_delim);
465             tmp = cliFormatReplyRaw(r->element[i]);
466             out = sdscatlen(out,tmp,sdslen(tmp));
467             sdsfree(tmp);
468         }
469         break;
470     default:
471         fprintf(stderr,"Unknown reply type: %d\n", r->type);
472         exit(1);
473     }
474     return out;
475 }
476 
477 static sds cliFormatReplyCSV(redisReply *r) {
478     unsigned int i;
479 
480     sds out = sdsempty();
481     switch (r->type) {
482     case REDIS_REPLY_ERROR:
483         out = sdscat(out,"ERROR,");
484         out = sdscatrepr(out,r->str,strlen(r->str));
485     break;
486     case REDIS_REPLY_STATUS:
487         out = sdscatrepr(out,r->str,r->len);
488     break;
489     case REDIS_REPLY_INTEGER:
490         out = sdscatprintf(out,"%lld",r->integer);
491     break;
492     case REDIS_REPLY_STRING:
493         out = sdscatrepr(out,r->str,r->len);
494     break;
495     case REDIS_REPLY_NIL:
496         out = sdscat(out,"NIL\n");
497     break;
498     case REDIS_REPLY_ARRAY:
499         for (i = 0; i < r->elements; i++) {
500             sds tmp = cliFormatReplyCSV(r->element[i]);
501             out = sdscatlen(out,tmp,sdslen(tmp));
502             if (i != r->elements-1) out = sdscat(out,",");
503             sdsfree(tmp);
504         }
505     break;
506     default:
507         fprintf(stderr,"Unknown reply type: %d\n", r->type);
508         exit(1);
509     }
510     return out;
511 }
512 
513 static int cliReadReply(int output_raw_strings) {
514     void *_reply;
515     redisReply *reply;
516     sds out = NULL;
517     int output = 1;
518 
519     if (redisGetReply(context,&_reply) != REDIS_OK) {
520         if (config.shutdown) {
521             redisFree(context);
522             context = NULL;
523             return REDIS_OK;
524         }
525         if (config.interactive) {
526             /* Filter cases where we should reconnect */
527             if (context->err == REDIS_ERR_IO &&
528                 (errno == ECONNRESET || errno == EPIPE))
529                 return REDIS_ERR;
530             if (context->err == REDIS_ERR_EOF)
531                 return REDIS_ERR;
532         }
533         cliPrintContextError();
534         exit(1);
535         return REDIS_ERR; /* avoid compiler warning */
536     }
537 
538     reply = (redisReply*)_reply;
539 
540     config.last_cmd_type = reply->type;
541 
542     /* Check if we need to connect to a different node and reissue the
543      * request. */
544     if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
545         (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
546     {
547         char *p = reply->str, *s;
548         int slot;
549 
550         output = 0;
551         /* Comments show the position of the pointer as:
552          *
553          * [S] for pointer 's'
554          * [P] for pointer 'p'
555          */
556         s = strchr(p,' ');      /* MOVED[S]3999 127.0.0.1:6381 */
557         p = strchr(s+1,' ');    /* MOVED[S]3999[P]127.0.0.1:6381 */
558         *p = '\0';
559         slot = atoi(s+1);
560         s = strchr(p+1,':');    /* MOVED 3999[P]127.0.0.1[S]6381 */
561         *s = '\0';
562         sdsfree(config.hostip);
563         config.hostip = sdsnew(p+1);
564         config.hostport = atoi(s+1);
565         if (config.interactive)
566             printf("-> Redirected to slot [%d] located at %s:%d\n",
567                 slot, config.hostip, config.hostport);
568         config.cluster_reissue_command = 1;
569         cliRefreshPrompt();
570     }
571 
572     if (output) {
573         if (output_raw_strings) {
574             out = cliFormatReplyRaw(reply);
575         } else {
576             if (config.output == OUTPUT_RAW) {
577                 out = cliFormatReplyRaw(reply);
578                 out = sdscat(out,"\n");
579             } else if (config.output == OUTPUT_STANDARD) {
580                 out = cliFormatReplyTTY(reply,"");
581             } else if (config.output == OUTPUT_CSV) {
582                 out = cliFormatReplyCSV(reply);
583                 out = sdscat(out,"\n");
584             }
585         }
586         fwrite(out,sdslen(out),1,stdout);
587         sdsfree(out);
588     }
589     freeReplyObject(reply);
590     return REDIS_OK;
591 }
592 
593 static int cliSendCommand(int argc, char **argv, int repeat) {
594     char *command = argv[0];
595     size_t *argvlen;
596     int j, output_raw;
597 
598     if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
599         cliOutputHelp(--argc, ++argv);
600         return REDIS_OK;
601     }
602 
603     if (context == NULL) return REDIS_ERR;
604 
605     output_raw = 0;
606     if (!strcasecmp(command,"info") ||
607         (argc == 2 && !strcasecmp(command,"cluster") &&
608                       (!strcasecmp(argv[1],"nodes") ||
609                        !strcasecmp(argv[1],"info"))) ||
610         (argc == 2 && !strcasecmp(command,"client") &&
611                        !strcasecmp(argv[1],"list")) ||
612         (argc == 3 && !strcasecmp(command,"latency") &&
613                        !strcasecmp(argv[1],"graph")) ||
614         (argc == 2 && !strcasecmp(command,"latency") &&
615                        !strcasecmp(argv[1],"doctor")))
616     {
617         output_raw = 1;
618     }
619 
620     if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
621     if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
622     if (!strcasecmp(command,"subscribe") ||
623         !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
624     if (!strcasecmp(command,"sync") ||
625         !strcasecmp(command,"psync")) config.slave_mode = 1;
626 
627     /* Setup argument length */
628     argvlen = malloc(argc*sizeof(size_t));
629     for (j = 0; j < argc; j++)
630         argvlen[j] = sdslen(argv[j]);
631 
632     while(repeat--) {
633         redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
634         while (config.monitor_mode) {
635             if (cliReadReply(output_raw) != REDIS_OK) exit(1);
636             fflush(stdout);
637         }
638 
639         if (config.pubsub_mode) {
640             if (config.output != OUTPUT_RAW)
641                 printf("Reading messages... (press Ctrl-C to quit)\n");
642             while (1) {
643                 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
644             }
645         }
646 
647         if (config.slave_mode) {
648             printf("Entering slave output mode...  (press Ctrl-C to quit)\n");
649             slaveMode();
650             config.slave_mode = 0;
651             free(argvlen);
652             return REDIS_ERR;  /* Error = slaveMode lost connection to master */
653         }
654 
655         if (cliReadReply(output_raw) != REDIS_OK) {
656             free(argvlen);
657             return REDIS_ERR;
658         } else {
659             /* Store database number when SELECT was successfully executed. */
660             if (!strcasecmp(command,"select") && argc == 2) {
661                 config.dbnum = atoi(argv[1]);
662                 cliRefreshPrompt();
663             } else if (!strcasecmp(command,"auth") && argc == 2) {
664                 cliSelect();
665             }
666         }
667         if (config.interval) usleep(config.interval);
668         fflush(stdout); /* Make it grep friendly */
669     }
670 
671     free(argvlen);
672     return REDIS_OK;
673 }
674 
675 /* Send the INFO command, reconnecting the link if needed. */
676 static redisReply *reconnectingInfo(void) {
677     redisContext *c = context;
678     redisReply *reply = NULL;
679     int tries = 0;
680 
681     assert(!c->err);
682     while(reply == NULL) {
683         while (c->err & (REDIS_ERR_IO | REDIS_ERR_EOF)) {
684             printf("Reconnecting (%d)...\r", ++tries);
685             fflush(stdout);
686 
687             redisFree(c);
688             c = redisConnect(config.hostip,config.hostport);
689             usleep(1000000);
690         }
691 
692         reply = redisCommand(c,"INFO");
693         if (c->err && !(c->err & (REDIS_ERR_IO | REDIS_ERR_EOF))) {
694             fprintf(stderr, "Error: %s\n", c->errstr);
695             exit(1);
696         } else if (tries > 0) {
697             printf("\n");
698         }
699     }
700 
701     context = c;
702     return reply;
703 }
704 
705 /*------------------------------------------------------------------------------
706  * User interface
707  *--------------------------------------------------------------------------- */
708 
709 static int parseOptions(int argc, char **argv) {
710     int i;
711 
712     for (i = 1; i < argc; i++) {
713         int lastarg = i==argc-1;
714 
715         if (!strcmp(argv[i],"-h") && !lastarg) {
716             sdsfree(config.hostip);
717             config.hostip = sdsnew(argv[++i]);
718         } else if (!strcmp(argv[i],"-h") && lastarg) {
719             usage();
720         } else if (!strcmp(argv[i],"--help")) {
721             usage();
722         } else if (!strcmp(argv[i],"-x")) {
723             config.stdinarg = 1;
724         } else if (!strcmp(argv[i],"-p") && !lastarg) {
725             config.hostport = atoi(argv[++i]);
726         } else if (!strcmp(argv[i],"-s") && !lastarg) {
727             config.hostsocket = argv[++i];
728         } else if (!strcmp(argv[i],"-r") && !lastarg) {
729             config.repeat = strtoll(argv[++i],NULL,10);
730         } else if (!strcmp(argv[i],"-i") && !lastarg) {
731             double seconds = atof(argv[++i]);
732             config.interval = seconds*1000000;
733         } else if (!strcmp(argv[i],"-n") && !lastarg) {
734             config.dbnum = atoi(argv[++i]);
735         } else if (!strcmp(argv[i],"-a") && !lastarg) {
736             config.auth = argv[++i];
737         } else if (!strcmp(argv[i],"--raw")) {
738             config.output = OUTPUT_RAW;
739         } else if (!strcmp(argv[i],"--no-raw")) {
740             config.output = OUTPUT_STANDARD;
741         } else if (!strcmp(argv[i],"--csv")) {
742             config.output = OUTPUT_CSV;
743         } else if (!strcmp(argv[i],"--latency")) {
744             config.latency_mode = 1;
745         } else if (!strcmp(argv[i],"--latency-history")) {
746             config.latency_mode = 1;
747             config.latency_history = 1;
748         } else if (!strcmp(argv[i],"--slave")) {
749             config.slave_mode = 1;
750         } else if (!strcmp(argv[i],"--stat")) {
751             config.stat_mode = 1;
752         } else if (!strcmp(argv[i],"--scan")) {
753             config.scan_mode = 1;
754         } else if (!strcmp(argv[i],"--pattern") && !lastarg) {
755             config.pattern = argv[++i];
756         } else if (!strcmp(argv[i],"--intrinsic-latency") && !lastarg) {
757             config.intrinsic_latency_mode = 1;
758             config.intrinsic_latency_duration = atoi(argv[++i]);
759         } else if (!strcmp(argv[i],"--rdb") && !lastarg) {
760             config.getrdb_mode = 1;
761             config.rdb_filename = argv[++i];
762         } else if (!strcmp(argv[i],"--pipe")) {
763             config.pipe_mode = 1;
764         } else if (!strcmp(argv[i],"--pipe-timeout") && !lastarg) {
765             config.pipe_timeout = atoi(argv[++i]);
766         } else if (!strcmp(argv[i],"--bigkeys")) {
767             config.bigkeys = 1;
768         } else if (!strcmp(argv[i],"--eval") && !lastarg) {
769             config.eval = argv[++i];
770         } else if (!strcmp(argv[i],"-c")) {
771             config.cluster_mode = 1;
772         } else if (!strcmp(argv[i],"-d") && !lastarg) {
773             sdsfree(config.mb_delim);
774             config.mb_delim = sdsnew(argv[++i]);
775         } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
776             sds version = cliVersion();
777             printf("redis-cli %s\n", version);
778             sdsfree(version);
779             exit(0);
780         } else {
781             if (argv[i][0] == '-') {
782                 fprintf(stderr,
783                     "Unrecognized option or bad number of args for: '%s'\n",
784                     argv[i]);
785                 exit(1);
786             } else {
787                 /* Likely the command name, stop here. */
788                 break;
789             }
790         }
791     }
792     return i;
793 }
794 
795 static sds readArgFromStdin(void) {
796     char buf[1024];
797     sds arg = sdsempty();
798 
799     while(1) {
800         int nread = read(fileno(stdin),buf,1024);
801 
802         if (nread == 0) break;
803         else if (nread == -1) {
804             perror("Reading from standard input");
805             exit(1);
806         }
807         arg = sdscatlen(arg,buf,nread);
808     }
809     return arg;
810 }
811 
812 static void usage(void) {
813     sds version = cliVersion();
814     fprintf(stderr,
815 "redis-cli %s\n"
816 "\n"
817 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
818 "  -h <hostname>      Server hostname (default: 127.0.0.1).\n"
819 "  -p <port>          Server port (default: 6379).\n"
820 "  -s <socket>        Server socket (overrides hostname and port).\n"
821 "  -a <password>      Password to use when connecting to the server.\n"
822 "  -r <repeat>        Execute specified command N times.\n"
823 "  -i <interval>      When -r is used, waits <interval> seconds per command.\n"
824 "                     It is possible to specify sub-second times like -i 0.1.\n"
825 "  -n <db>            Database number.\n"
826 "  -x                 Read last argument from STDIN.\n"
827 "  -d <delimiter>     Multi-bulk delimiter in for raw formatting (default: \\n).\n"
828 "  -c                 Enable cluster mode (follow -ASK and -MOVED redirections).\n"
829 "  --raw              Use raw formatting for replies (default when STDOUT is\n"
830 "                     not a tty).\n"
831 "  --no-raw           Force formatted output even when STDOUT is not a tty.\n"
832 "  --csv              Output in CSV format.\n"
833 "  --latency          Enter a special mode continuously sampling latency.\n"
834 "  --latency-history  Like --latency but tracking latency changes over time.\n"
835 "                     Default time interval is 15 sec. Change it using -i.\n"
836 "  --slave            Simulate a slave showing commands received from the master.\n"
837 "  --rdb <filename>   Transfer an RDB dump from remote server to local file.\n"
838 "  --pipe             Transfer raw Redis protocol from stdin to server.\n"
839 "  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.\n"
840 "                     no reply is received within <n> seconds.\n"
841 "                     Default timeout: %d. Use 0 to wait forever.\n"
842 "  --bigkeys          Sample Redis keys looking for big keys.\n"
843 "  --scan             List all keys using the SCAN command.\n"
844 "  --pattern <pat>    Useful with --scan to specify a SCAN pattern.\n"
845 "  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.\n"
846 "                     The test will run for the specified amount of seconds.\n"
847 "  --eval <file>      Send an EVAL command using the Lua script at <file>.\n"
848 "  --help             Output this help and exit.\n"
849 "  --version          Output version and exit.\n"
850 "\n"
851 "Examples:\n"
852 "  cat /etc/passwd | redis-cli -x set mypasswd\n"
853 "  redis-cli get mypasswd\n"
854 "  redis-cli -r 100 lpush mylist x\n"
855 "  redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
856 "  redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
857 "  redis-cli --scan --pattern '*:12345*'\n"
858 "\n"
859 "  (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
860 "\n"
861 "When no command is given, redis-cli starts in interactive mode.\n"
862 "Type \"help\" in interactive mode for information on available commands.\n"
863 "\n",
864         version, REDIS_CLI_DEFAULT_PIPE_TIMEOUT);
865     sdsfree(version);
866     exit(1);
867 }
868 
869 /* Turn the plain C strings into Sds strings */
870 static char **convertToSds(int count, char** args) {
871   int j;
872   char **sds = zmalloc(sizeof(char*)*count);
873 
874   for(j = 0; j < count; j++)
875     sds[j] = sdsnew(args[j]);
876 
877   return sds;
878 }
879 
880 static void repl(void) {
881     sds historyfile = NULL;
882     int history = 0;
883     char *line;
884     int argc;
885     sds *argv;
886 
887     config.interactive = 1;
888     linenoiseSetMultiLine(1);
889     linenoiseSetCompletionCallback(completionCallback);
890 
891     /* Only use history when stdin is a tty. */
892     if (isatty(fileno(stdin))) {
893         history = 1;
894 
895         if (getenv("HOME") != NULL) {
896             historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
897             linenoiseHistoryLoad(historyfile);
898         }
899     }
900 
901     cliRefreshPrompt();
902     while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
903         if (line[0] != '\0') {
904             argv = sdssplitargs(line,&argc);
905             if (history) linenoiseHistoryAdd(line);
906             if (historyfile) linenoiseHistorySave(historyfile);
907 
908             if (argv == NULL) {
909                 printf("Invalid argument(s)\n");
910                 free(line);
911                 continue;
912             } else if (argc > 0) {
913                 if (strcasecmp(argv[0],"quit") == 0 ||
914                     strcasecmp(argv[0],"exit") == 0)
915                 {
916                     exit(0);
917                 } else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
918                     sdsfree(config.hostip);
919                     config.hostip = sdsnew(argv[1]);
920                     config.hostport = atoi(argv[2]);
921                     cliRefreshPrompt();
922                     cliConnect(1);
923                 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
924                     linenoiseClearScreen();
925                 } else {
926                     long long start_time = mstime(), elapsed;
927                     int repeat, skipargs = 0;
928 
929                     repeat = atoi(argv[0]);
930                     if (argc > 1 && repeat) {
931                         skipargs = 1;
932                     } else {
933                         repeat = 1;
934                     }
935 
936                     while (1) {
937                         config.cluster_reissue_command = 0;
938                         if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
939                             != REDIS_OK)
940                         {
941                             cliConnect(1);
942 
943                             /* If we still cannot send the command print error.
944                              * We'll try to reconnect the next time. */
945                             if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
946                                 != REDIS_OK)
947                                 cliPrintContextError();
948                         }
949                         /* Issue the command again if we got redirected in cluster mode */
950                         if (config.cluster_mode && config.cluster_reissue_command) {
951                             cliConnect(1);
952                         } else {
953                             break;
954                         }
955                     }
956                     elapsed = mstime()-start_time;
957                     if (elapsed >= 500) {
958                         printf("(%.2fs)\n",(double)elapsed/1000);
959                     }
960                 }
961             }
962             /* Free the argument vector */
963             sdsfreesplitres(argv,argc);
964         }
965         /* linenoise() returns malloc-ed lines like readline() */
966         free(line);
967     }
968     exit(0);
969 }
970 
971 static int noninteractive(int argc, char **argv) {
972     int retval = 0;
973     if (config.stdinarg) {
974         argv = zrealloc(argv, (argc+1)*sizeof(char*));
975         argv[argc] = readArgFromStdin();
976         retval = cliSendCommand(argc+1, argv, config.repeat);
977     } else {
978         /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
979         retval = cliSendCommand(argc, argv, config.repeat);
980     }
981     return retval;
982 }
983 
984 /*------------------------------------------------------------------------------
985  * Eval mode
986  *--------------------------------------------------------------------------- */
987 
988 static int evalMode(int argc, char **argv) {
989     sds script = sdsempty();
990     FILE *fp;
991     char buf[1024];
992     size_t nread;
993     char **argv2;
994     int j, got_comma = 0, keys = 0;
995 
996     /* Load the script from the file, as an sds string. */
997     fp = fopen(config.eval,"r");
998     if (!fp) {
999         fprintf(stderr,
1000             "Can't open file '%s': %s\n", config.eval, strerror(errno));
1001         exit(1);
1002     }
1003     while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
1004         script = sdscatlen(script,buf,nread);
1005     }
1006     fclose(fp);
1007 
1008     /* Create our argument vector */
1009     argv2 = zmalloc(sizeof(sds)*(argc+3));
1010     argv2[0] = sdsnew("EVAL");
1011     argv2[1] = script;
1012     for (j = 0; j < argc; j++) {
1013         if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
1014             got_comma = 1;
1015             continue;
1016         }
1017         argv2[j+3-got_comma] = sdsnew(argv[j]);
1018         if (!got_comma) keys++;
1019     }
1020     argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
1021 
1022     /* Call it */
1023     return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
1024 }
1025 
1026 /*------------------------------------------------------------------------------
1027  * Latency and latency history modes
1028  *--------------------------------------------------------------------------- */
1029 
1030 #define LATENCY_SAMPLE_RATE 10 /* milliseconds. */
1031 #define LATENCY_HISTORY_DEFAULT_INTERVAL 15000 /* milliseconds. */
1032 static void latencyMode(void) {
1033     redisReply *reply;
1034     long long start, latency, min = 0, max = 0, tot = 0, count = 0;
1035     long long history_interval =
1036         config.interval ? config.interval/1000 :
1037                           LATENCY_HISTORY_DEFAULT_INTERVAL;
1038     double avg;
1039     long long history_start = mstime();
1040 
1041     if (!context) exit(1);
1042     while(1) {
1043         start = mstime();
1044         reply = redisCommand(context,"PING");
1045         if (reply == NULL) {
1046             fprintf(stderr,"\nI/O error\n");
1047             exit(1);
1048         }
1049         latency = mstime()-start;
1050         freeReplyObject(reply);
1051         count++;
1052         if (count == 1) {
1053             min = max = tot = latency;
1054             avg = (double) latency;
1055         } else {
1056             if (latency < min) min = latency;
1057             if (latency > max) max = latency;
1058             tot += latency;
1059             avg = (double) tot/count;
1060         }
1061         printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
1062             min, max, avg, count);
1063         fflush(stdout);
1064         if (config.latency_history && mstime()-history_start > history_interval)
1065         {
1066             printf(" -- %.2f seconds range\n", (float)(mstime()-history_start)/1000);
1067             history_start = mstime();
1068             min = max = tot = count = 0;
1069         }
1070         usleep(LATENCY_SAMPLE_RATE * 1000);
1071     }
1072 }
1073 
1074 /*------------------------------------------------------------------------------
1075  * Slave mode
1076  *--------------------------------------------------------------------------- */
1077 
1078 /* Sends SYNC and reads the number of bytes in the payload. Used both by
1079  * slaveMode() and getRDB(). */
1080 unsigned long long sendSync(int fd) {
1081     /* To start we need to send the SYNC command and return the payload.
1082      * The hiredis client lib does not understand this part of the protocol
1083      * and we don't want to mess with its buffers, so everything is performed
1084      * using direct low-level I/O. */
1085     char buf[4096], *p;
1086     ssize_t nread;
1087 
1088     /* Send the SYNC command. */
1089     if (write(fd,"SYNC\r\n",6) != 6) {
1090         fprintf(stderr,"Error writing to master\n");
1091         exit(1);
1092     }
1093 
1094     /* Read $<payload>\r\n, making sure to read just up to "\n" */
1095     p = buf;
1096     while(1) {
1097         nread = read(fd,p,1);
1098         if (nread <= 0) {
1099             fprintf(stderr,"Error reading bulk length while SYNCing\n");
1100             exit(1);
1101         }
1102         if (*p == '\n' && p != buf) break;
1103         if (*p != '\n') p++;
1104     }
1105     *p = '\0';
1106     if (buf[0] == '-') {
1107         printf("SYNC with master failed: %s\n", buf);
1108         exit(1);
1109     }
1110     return strtoull(buf+1,NULL,10);
1111 }
1112 
1113 static void slaveMode(void) {
1114     int fd = context->fd;
1115     unsigned long long payload = sendSync(fd);
1116     char buf[1024];
1117     int original_output = config.output;
1118 
1119     fprintf(stderr,"SYNC with master, discarding %llu "
1120                    "bytes of bulk transfer...\n", payload);
1121 
1122     /* Discard the payload. */
1123     while(payload) {
1124         ssize_t nread;
1125 
1126         nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
1127         if (nread <= 0) {
1128             fprintf(stderr,"Error reading RDB payload while SYNCing\n");
1129             exit(1);
1130         }
1131         payload -= nread;
1132     }
1133     fprintf(stderr,"SYNC done. Logging commands from master.\n");
1134 
1135     /* Now we can use hiredis to read the incoming protocol. */
1136     config.output = OUTPUT_CSV;
1137     while (cliReadReply(0) == REDIS_OK);
1138     config.output = original_output;
1139 }
1140 
1141 /*------------------------------------------------------------------------------
1142  * RDB transfer mode
1143  *--------------------------------------------------------------------------- */
1144 
1145 /* This function implements --rdb, so it uses the replication protocol in order
1146  * to fetch the RDB file from a remote server. */
1147 static void getRDB(void) {
1148     int s = context->fd;
1149     int fd;
1150     unsigned long long payload = sendSync(s);
1151     char buf[4096];
1152 
1153     fprintf(stderr,"SYNC sent to master, writing %llu bytes to '%s'\n",
1154         payload, config.rdb_filename);
1155 
1156     /* Write to file. */
1157     if (!strcmp(config.rdb_filename,"-")) {
1158         fd = STDOUT_FILENO;
1159     } else {
1160         fd = open(config.rdb_filename, O_CREAT|O_WRONLY, 0644);
1161         if (fd == -1) {
1162             fprintf(stderr, "Error opening '%s': %s\n", config.rdb_filename,
1163                 strerror(errno));
1164             exit(1);
1165         }
1166     }
1167 
1168     while(payload) {
1169         ssize_t nread, nwritten;
1170 
1171         nread = read(s,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload);
1172         if (nread <= 0) {
1173             fprintf(stderr,"I/O Error reading RDB payload from socket\n");
1174             exit(1);
1175         }
1176         nwritten = write(fd, buf, nread);
1177         if (nwritten != nread) {
1178             fprintf(stderr,"Error writing data to file: %s\n",
1179                 strerror(errno));
1180             exit(1);
1181         }
1182         payload -= nread;
1183     }
1184     close(s); /* Close the file descriptor ASAP as fsync() may take time. */
1185     fsync(fd);
1186     fprintf(stderr,"Transfer finished with success.\n");
1187     exit(0);
1188 }
1189 
1190 /*------------------------------------------------------------------------------
1191  * Bulk import (pipe) mode
1192  *--------------------------------------------------------------------------- */
1193 
1194 static void pipeMode(void) {
1195     int fd = context->fd;
1196     long long errors = 0, replies = 0, obuf_len = 0, obuf_pos = 0;
1197     char ibuf[1024*16], obuf[1024*16]; /* Input and output buffers */
1198     char aneterr[ANET_ERR_LEN];
1199     redisReader *reader = redisReaderCreate();
1200     redisReply *reply;
1201     int eof = 0; /* True once we consumed all the standard input. */
1202     int done = 0;
1203     char magic[20]; /* Special reply we recognize. */
1204     time_t last_read_time = time(NULL);
1205 
1206     srand(time(NULL));
1207 
1208     /* Use non blocking I/O. */
1209     if (anetNonBlock(aneterr,fd) == ANET_ERR) {
1210         fprintf(stderr, "Can't set the socket in non blocking mode: %s\n",
1211             aneterr);
1212         exit(1);
1213     }
1214 
1215     /* Transfer raw protocol and read replies from the server at the same
1216      * time. */
1217     while(!done) {
1218         int mask = AE_READABLE;
1219 
1220         if (!eof || obuf_len != 0) mask |= AE_WRITABLE;
1221         mask = aeWait(fd,mask,1000);
1222 
1223         /* Handle the readable state: we can read replies from the server. */
1224         if (mask & AE_READABLE) {
1225             ssize_t nread;
1226 
1227             /* Read from socket and feed the hiredis reader. */
1228             do {
1229                 nread = read(fd,ibuf,sizeof(ibuf));
1230                 if (nread == -1 && errno != EAGAIN && errno != EINTR) {
1231                     fprintf(stderr, "Error reading from the server: %s\n",
1232                         strerror(errno));
1233                     exit(1);
1234                 }
1235                 if (nread > 0) {
1236                     redisReaderFeed(reader,ibuf,nread);
1237                     last_read_time = time(NULL);
1238                 }
1239             } while(nread > 0);
1240 
1241             /* Consume replies. */
1242             do {
1243                 if (redisReaderGetReply(reader,(void**)&reply) == REDIS_ERR) {
1244                     fprintf(stderr, "Error reading replies from server\n");
1245                     exit(1);
1246                 }
1247                 if (reply) {
1248                     if (reply->type == REDIS_REPLY_ERROR) {
1249                         fprintf(stderr,"%s\n", reply->str);
1250                         errors++;
1251                     } else if (eof && reply->type == REDIS_REPLY_STRING &&
1252                                       reply->len == 20) {
1253                         /* Check if this is the reply to our final ECHO
1254                          * command. If so everything was received
1255                          * from the server. */
1256                         if (memcmp(reply->str,magic,20) == 0) {
1257                             printf("Last reply received from server.\n");
1258                             done = 1;
1259                             replies--;
1260                         }
1261                     }
1262                     replies++;
1263                     freeReplyObject(reply);
1264                 }
1265             } while(reply);
1266         }
1267 
1268         /* Handle the writable state: we can send protocol to the server. */
1269         if (mask & AE_WRITABLE) {
1270             while(1) {
1271                 /* Transfer current buffer to server. */
1272                 if (obuf_len != 0) {
1273                     ssize_t nwritten = write(fd,obuf+obuf_pos,obuf_len);
1274 
1275                     if (nwritten == -1) {
1276                         if (errno != EAGAIN && errno != EINTR) {
1277                             fprintf(stderr, "Error writing to the server: %s\n",
1278                                 strerror(errno));
1279                             exit(1);
1280                         } else {
1281                             nwritten = 0;
1282                         }
1283                     }
1284                     obuf_len -= nwritten;
1285                     obuf_pos += nwritten;
1286                     if (obuf_len != 0) break; /* Can't accept more data. */
1287                 }
1288                 /* If buffer is empty, load from stdin. */
1289                 if (obuf_len == 0 && !eof) {
1290                     ssize_t nread = read(STDIN_FILENO,obuf,sizeof(obuf));
1291 
1292                     if (nread == 0) {
1293                         /* The ECHO sequence starts with a "\r\n" so that if there
1294                          * is garbage in the protocol we read from stdin, the ECHO
1295                          * will likely still be properly formatted.
1296                          * CRLF is ignored by Redis, so it has no effects. */
1297                         char echo[] =
1298                         "\r\n*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n";
1299                         int j;
1300 
1301                         eof = 1;
1302                         /* Everything transferred, so we queue a special
1303                          * ECHO command that we can match in the replies
1304                          * to make sure everything was read from the server. */
1305                         for (j = 0; j < 20; j++)
1306                             magic[j] = rand() & 0xff;
1307                         memcpy(echo+21,magic,20);
1308                         memcpy(obuf,echo,sizeof(echo)-1);
1309                         obuf_len = sizeof(echo)-1;
1310                         obuf_pos = 0;
1311                         printf("All data transferred. Waiting for the last reply...\n");
1312                     } else if (nread == -1) {
1313                         fprintf(stderr, "Error reading from stdin: %s\n",
1314                             strerror(errno));
1315                         exit(1);
1316                     } else {
1317                         obuf_len = nread;
1318                         obuf_pos = 0;
1319                     }
1320                 }
1321                 if (obuf_len == 0 && eof) break;
1322             }
1323         }
1324 
1325         /* Handle timeout, that is, we reached EOF, and we are not getting
1326          * replies from the server for a few seconds, nor the final ECHO is
1327          * received. */
1328         if (eof && config.pipe_timeout > 0 &&
1329             time(NULL)-last_read_time > config.pipe_timeout)
1330         {
1331             fprintf(stderr,"No replies for %d seconds: exiting.\n",
1332                 config.pipe_timeout);
1333             errors++;
1334             break;
1335         }
1336     }
1337     redisReaderFree(reader);
1338     printf("errors: %lld, replies: %lld\n", errors, replies);
1339     if (errors)
1340         exit(1);
1341     else
1342         exit(0);
1343 }
1344 
1345 /*------------------------------------------------------------------------------
1346  * Find big keys
1347  *--------------------------------------------------------------------------- */
1348 
1349 #define TYPE_STRING 0
1350 #define TYPE_LIST   1
1351 #define TYPE_SET    2
1352 #define TYPE_HASH   3
1353 #define TYPE_ZSET   4
1354 #define TYPE_NONE   5
1355 
1356 static redisReply *sendScan(unsigned long long *it) {
1357     redisReply *reply = redisCommand(context, "SCAN %llu", *it);
1358 
1359     /* Handle any error conditions */
1360     if(reply == NULL) {
1361         fprintf(stderr, "\nI/O error\n");
1362         exit(1);
1363     } else if(reply->type == REDIS_REPLY_ERROR) {
1364         fprintf(stderr, "SCAN error: %s\n", reply->str);
1365         exit(1);
1366     } else if(reply->type != REDIS_REPLY_ARRAY) {
1367         fprintf(stderr, "Non ARRAY response from SCAN!\n");
1368         exit(1);
1369     } else if(reply->elements != 2) {
1370         fprintf(stderr, "Invalid element count from SCAN!\n");
1371         exit(1);
1372     }
1373 
1374     /* Validate our types are correct */
1375     assert(reply->element[0]->type == REDIS_REPLY_STRING);
1376     assert(reply->element[1]->type == REDIS_REPLY_ARRAY);
1377 
1378     /* Update iterator */
1379     *it = atoi(reply->element[0]->str);
1380 
1381     return reply;
1382 }
1383 
1384 static int getDbSize(void) {
1385     redisReply *reply;
1386     int size;
1387 
1388     reply = redisCommand(context, "DBSIZE");
1389 
1390     if(reply == NULL || reply->type != REDIS_REPLY_INTEGER) {
1391         fprintf(stderr, "Couldn't determine DBSIZE!\n");
1392         exit(1);
1393     }
1394 
1395     /* Grab the number of keys and free our reply */
1396     size = reply->integer;
1397     freeReplyObject(reply);
1398 
1399     return size;
1400 }
1401 
1402 static int toIntType(char *key, char *type) {
1403     if(!strcmp(type, "string")) {
1404         return TYPE_STRING;
1405     } else if(!strcmp(type, "list")) {
1406         return TYPE_LIST;
1407     } else if(!strcmp(type, "set")) {
1408         return TYPE_SET;
1409     } else if(!strcmp(type, "hash")) {
1410         return TYPE_HASH;
1411     } else if(!strcmp(type, "zset")) {
1412         return TYPE_ZSET;
1413     } else if(!strcmp(type, "none")) {
1414         return TYPE_NONE;
1415     } else {
1416         fprintf(stderr, "Unknown type '%s' for key '%s'\n", type, key);
1417         exit(1);
1418     }
1419 }
1420 
1421 static void getKeyTypes(redisReply *keys, int *types) {
1422     redisReply *reply;
1423     unsigned int i;
1424 
1425     /* Pipeline TYPE commands */
1426     for(i=0;i<keys->elements;i++) {
1427         redisAppendCommand(context, "TYPE %s", keys->element[i]->str);
1428     }
1429 
1430     /* Retrieve types */
1431     for(i=0;i<keys->elements;i++) {
1432         if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
1433             fprintf(stderr, "Error getting type for key '%s' (%d: %s)\n",
1434                 keys->element[i]->str, context->err, context->errstr);
1435             exit(1);
1436         } else if(reply->type != REDIS_REPLY_STATUS) {
1437             fprintf(stderr, "Invalid reply type (%d) for TYPE on key '%s'!\n",
1438                 reply->type, keys->element[i]->str);
1439             exit(1);
1440         }
1441 
1442         types[i] = toIntType(keys->element[i]->str, reply->str);
1443         freeReplyObject(reply);
1444     }
1445 }
1446 
1447 static void getKeySizes(redisReply *keys, int *types,
1448                         unsigned long long *sizes)
1449 {
1450     redisReply *reply;
1451     char *sizecmds[] = {"STRLEN","LLEN","SCARD","HLEN","ZCARD"};
1452     unsigned int i;
1453 
1454     /* Pipeline size commands */
1455     for(i=0;i<keys->elements;i++) {
1456         /* Skip keys that were deleted */
1457         if(types[i]==TYPE_NONE)
1458             continue;
1459 
1460         redisAppendCommand(context, "%s %s", sizecmds[types[i]],
1461             keys->element[i]->str);
1462     }
1463 
1464     /* Retreive sizes */
1465     for(i=0;i<keys->elements;i++) {
1466         /* Skip keys that dissapeared between SCAN and TYPE */
1467         if(types[i] == TYPE_NONE) {
1468             sizes[i] = 0;
1469             continue;
1470         }
1471 
1472         /* Retreive size */
1473         if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
1474             fprintf(stderr, "Error getting size for key '%s' (%d: %s)\n",
1475                 keys->element[i]->str, context->err, context->errstr);
1476             exit(1);
1477         } else if(reply->type != REDIS_REPLY_INTEGER) {
1478             /* Theoretically the key could have been removed and
1479              * added as a different type between TYPE and SIZE */
1480             fprintf(stderr,
1481                 "Warning:  %s on '%s' failed (may have changed type)\n",
1482                  sizecmds[types[i]], keys->element[i]->str);
1483             sizes[i] = 0;
1484         } else {
1485             sizes[i] = reply->integer;
1486         }
1487 
1488         freeReplyObject(reply);
1489     }
1490 }
1491 
1492 static void findBigKeys(void) {
1493     unsigned long long biggest[5] = {0}, counts[5] = {0}, totalsize[5] = {0};
1494     unsigned long long sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0;
1495     sds maxkeys[5] = {0};
1496     char *typename[] = {"string","list","set","hash","zset"};
1497     char *typeunit[] = {"bytes","items","members","fields","members"};
1498     redisReply *reply, *keys;
1499     unsigned int arrsize=0, i;
1500     int type, *types=NULL;
1501     double pct;
1502 
1503     /* Total keys pre scanning */
1504     total_keys = getDbSize();
1505 
1506     /* Status message */
1507     printf("\n# Scanning the entire keyspace to find biggest keys as well as\n");
1508     printf("# average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec\n");
1509     printf("# per 100 SCAN commands (not usually needed).\n\n");
1510 
1511     /* New up sds strings to keep track of overall biggest per type */
1512     for(i=0;i<TYPE_NONE; i++) {
1513         maxkeys[i] = sdsempty();
1514         if(!maxkeys[i]) {
1515             fprintf(stderr, "Failed to allocate memory for largest key names!\n");
1516             exit(1);
1517         }
1518     }
1519 
1520     /* SCAN loop */
1521     do {
1522         /* Calculate approximate percentage completion */
1523         pct = 100 * (double)sampled/total_keys;
1524 
1525         /* Grab some keys and point to the keys array */
1526         reply = sendScan(&it);
1527         keys  = reply->element[1];
1528 
1529         /* Reallocate our type and size array if we need to */
1530         if(keys->elements > arrsize) {
1531             types = zrealloc(types, sizeof(int)*keys->elements);
1532             sizes = zrealloc(sizes, sizeof(unsigned long long)*keys->elements);
1533 
1534             if(!types || !sizes) {
1535                 fprintf(stderr, "Failed to allocate storage for keys!\n");
1536                 exit(1);
1537             }
1538 
1539             arrsize = keys->elements;
1540         }
1541 
1542         /* Retreive types and then sizes */
1543         getKeyTypes(keys, types);
1544         getKeySizes(keys, types, sizes);
1545 
1546         /* Now update our stats */
1547         for(i=0;i<keys->elements;i++) {
1548             if((type = types[i]) == TYPE_NONE)
1549                 continue;
1550 
1551             totalsize[type] += sizes[i];
1552             counts[type]++;
1553             totlen += keys->element[i]->len;
1554             sampled++;
1555 
1556             if(biggest[type]<sizes[i]) {
1557                 printf(
1558                    "[%05.2f%%] Biggest %-6s found so far '%s' with %llu %s\n",
1559                    pct, typename[type], keys->element[i]->str, sizes[i],
1560                    typeunit[type]);
1561 
1562                 /* Keep track of biggest key name for this type */
1563                 maxkeys[type] = sdscpy(maxkeys[type], keys->element[i]->str);
1564                 if(!maxkeys[type]) {
1565                     fprintf(stderr, "Failed to allocate memory for key!\n");
1566                     exit(1);
1567                 }
1568 
1569                 /* Keep track of the biggest size for this type */
1570                 biggest[type] = sizes[i];
1571             }
1572 
1573             /* Update overall progress */
1574             if(sampled % 1000000 == 0) {
1575                 printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled);
1576             }
1577         }
1578 
1579         /* Sleep if we've been directed to do so */
1580         if(sampled && (sampled %100) == 0 && config.interval) {
1581             usleep(config.interval);
1582         }
1583 
1584         freeReplyObject(reply);
1585     } while(it != 0);
1586 
1587     if(types) zfree(types);
1588     if(sizes) zfree(sizes);
1589 
1590     /* We're done */
1591     printf("\n-------- summary -------\n\n");
1592 
1593     printf("Sampled %llu keys in the keyspace!\n", sampled);
1594     printf("Total key length in bytes is %llu (avg len %.2f)\n\n",
1595        totlen, totlen ? (double)totlen/sampled : 0);
1596 
1597     /* Output the biggest keys we found, for types we did find */
1598     for(i=0;i<TYPE_NONE;i++) {
1599         if(sdslen(maxkeys[i])>0) {
1600             printf("Biggest %6s found '%s' has %llu %s\n", typename[i], maxkeys[i],
1601                biggest[i], typeunit[i]);
1602         }
1603     }
1604 
1605     printf("\n");
1606 
1607     for(i=0;i<TYPE_NONE;i++) {
1608         printf("%llu %ss with %llu %s (%05.2f%% of keys, avg size %.2f)\n",
1609            counts[i], typename[i], totalsize[i], typeunit[i],
1610            sampled ? 100 * (double)counts[i]/sampled : 0,
1611            counts[i] ? (double)totalsize[i]/counts[i] : 0);
1612     }
1613 
1614     /* Free sds strings containing max keys */
1615     for(i=0;i<TYPE_NONE;i++) {
1616         sdsfree(maxkeys[i]);
1617     }
1618 
1619     /* Success! */
1620     exit(0);
1621 }
1622 
1623 /*------------------------------------------------------------------------------
1624  * Stats mode
1625  *--------------------------------------------------------------------------- */
1626 
1627 /* Return the specified INFO field from the INFO command output "info".
1628  * A new buffer is allocated for the result, that needs to be free'd.
1629  * If the field is not found NULL is returned. */
1630 static char *getInfoField(char *info, char *field) {
1631     char *p = strstr(info,field);
1632     char *n1, *n2;
1633     char *result;
1634 
1635     if (!p) return NULL;
1636     p += strlen(field)+1;
1637     n1 = strchr(p,'\r');
1638     n2 = strchr(p,',');
1639     if (n2 && n2 < n1) n1 = n2;
1640     result = malloc(sizeof(char)*(n1-p)+1);
1641     memcpy(result,p,(n1-p));
1642     result[n1-p] = '\0';
1643     return result;
1644 }
1645 
1646 /* Like the above function but automatically convert the result into
1647  * a long. On error (missing field) LONG_MIN is returned. */
1648 static long getLongInfoField(char *info, char *field) {
1649     char *value = getInfoField(info,field);
1650     long l;
1651 
1652     if (!value) return LONG_MIN;
1653     l = strtol(value,NULL,10);
1654     free(value);
1655     return l;
1656 }
1657 
1658 /* Convert number of bytes into a human readable string of the form:
1659  * 100B, 2G, 100M, 4K, and so forth. */
1660 void bytesToHuman(char *s, long long n) {
1661     double d;
1662 
1663     if (n < 0) {
1664         *s = '-';
1665         s++;
1666         n = -n;
1667     }
1668     if (n < 1024) {
1669         /* Bytes */
1670         sprintf(s,"%lluB",n);
1671         return;
1672     } else if (n < (1024*1024)) {
1673         d = (double)n/(1024);
1674         sprintf(s,"%.2fK",d);
1675     } else if (n < (1024LL*1024*1024)) {
1676         d = (double)n/(1024*1024);
1677         sprintf(s,"%.2fM",d);
1678     } else if (n < (1024LL*1024*1024*1024)) {
1679         d = (double)n/(1024LL*1024*1024);
1680         sprintf(s,"%.2fG",d);
1681     }
1682 }
1683 
1684 static void statMode(void) {
1685     redisReply *reply;
1686     long aux, requests = 0;
1687     int i = 0;
1688 
1689     while(1) {
1690         char buf[64];
1691         int j;
1692 
1693         reply = reconnectingInfo();
1694         if (reply->type == REDIS_REPLY_ERROR) {
1695             printf("ERROR: %s\n", reply->str);
1696             exit(1);
1697         }
1698 
1699         if ((i++ % 20) == 0) {
1700             printf(
1701 "------- data ------ --------------------- load -------------------- - child -\n"
1702 "keys       mem      clients blocked requests            connections          \n");
1703         }
1704 
1705         /* Keys */
1706         aux = 0;
1707         for (j = 0; j < 20; j++) {
1708             long k;
1709 
1710             sprintf(buf,"db%d:keys",j);
1711             k = getLongInfoField(reply->str,buf);
1712             if (k == LONG_MIN) continue;
1713             aux += k;
1714         }
1715         sprintf(buf,"%ld",aux);
1716         printf("%-11s",buf);
1717 
1718         /* Used memory */
1719         aux = getLongInfoField(reply->str,"used_memory");
1720         bytesToHuman(buf,aux);
1721         printf("%-8s",buf);
1722 
1723         /* Clients */
1724         aux = getLongInfoField(reply->str,"connected_clients");
1725         sprintf(buf,"%ld",aux);
1726         printf(" %-8s",buf);
1727 
1728         /* Blocked (BLPOPPING) Clients */
1729         aux = getLongInfoField(reply->str,"blocked_clients");
1730         sprintf(buf,"%ld",aux);
1731         printf("%-8s",buf);
1732 
1733         /* Requets */
1734         aux = getLongInfoField(reply->str,"total_commands_processed");
1735         sprintf(buf,"%ld (+%ld)",aux,requests == 0 ? 0 : aux-requests);
1736         printf("%-19s",buf);
1737         requests = aux;
1738 
1739         /* Connections */
1740         aux = getLongInfoField(reply->str,"total_connections_received");
1741         sprintf(buf,"%ld",aux);
1742         printf(" %-12s",buf);
1743 
1744         /* Children */
1745         aux = getLongInfoField(reply->str,"bgsave_in_progress");
1746         aux |= getLongInfoField(reply->str,"aof_rewrite_in_progress") << 1;
1747         switch(aux) {
1748         case 0: break;
1749         case 1:
1750             printf("SAVE");
1751             break;
1752         case 2:
1753             printf("AOF");
1754             break;
1755         case 3:
1756             printf("SAVE+AOF");
1757             break;
1758         }
1759 
1760         printf("\n");
1761         freeReplyObject(reply);
1762         usleep(config.interval);
1763     }
1764 }
1765 
1766 /*------------------------------------------------------------------------------
1767  * Scan mode
1768  *--------------------------------------------------------------------------- */
1769 
1770 static void scanMode(void) {
1771     redisReply *reply;
1772     unsigned long long cur = 0;
1773 
1774     do {
1775         if (config.pattern)
1776             reply = redisCommand(context,"SCAN %llu MATCH %s",
1777                 cur,config.pattern);
1778         else
1779             reply = redisCommand(context,"SCAN %llu",cur);
1780         if (reply == NULL) {
1781             printf("I/O error\n");
1782             exit(1);
1783         } else if (reply->type == REDIS_REPLY_ERROR) {
1784             printf("ERROR: %s\n", reply->str);
1785             exit(1);
1786         } else {
1787             unsigned int j;
1788 
1789             cur = strtoull(reply->element[0]->str,NULL,10);
1790             for (j = 0; j < reply->element[1]->elements; j++)
1791                 printf("%s\n", reply->element[1]->element[j]->str);
1792         }
1793         freeReplyObject(reply);
1794     } while(cur != 0);
1795 
1796     exit(0);
1797 }
1798 
1799 /*------------------------------------------------------------------------------
1800  * Intrisic latency mode.
1801  *
1802  * Measure max latency of a running process that does not result from
1803  * syscalls. Basically this software should provide an hint about how much
1804  * time the kernel leaves the process without a chance to run.
1805  *--------------------------------------------------------------------------- */
1806 
1807 /* This is just some computation the compiler can't optimize out.
1808  * Should run in less than 100-200 microseconds even using very
1809  * slow hardware. Runs in less than 10 microseconds in modern HW. */
1810 unsigned long compute_something_fast(void) {
1811     unsigned char s[256], i, j, t;
1812     int count = 1000, k;
1813     unsigned long output = 0;
1814 
1815     for (k = 0; k < 256; k++) s[k] = k;
1816 
1817     i = 0;
1818     j = 0;
1819     while(count--) {
1820         i++;
1821         j = j + s[i];
1822         t = s[i];
1823         s[i] = s[j];
1824         s[j] = t;
1825         output += s[(s[i]+s[j])&255];
1826     }
1827     return output;
1828 }
1829 
1830 static void intrinsicLatencyModeStop(int s) {
1831     REDIS_NOTUSED(s);
1832     force_cancel_loop = 1;
1833 }
1834 
1835 static void intrinsicLatencyMode(void) {
1836     long long test_end, run_time, max_latency = 0, runs = 0;
1837 
1838     run_time = config.intrinsic_latency_duration*1000000;
1839     test_end = ustime() + run_time;
1840     signal(SIGINT, intrinsicLatencyModeStop);
1841 
1842     while(1) {
1843         long long start, end, latency;
1844 
1845         start = ustime();
1846         compute_something_fast();
1847         end = ustime();
1848         latency = end-start;
1849         runs++;
1850         if (latency <= 0) continue;
1851 
1852         /* Reporting */
1853         if (latency > max_latency) {
1854             max_latency = latency;
1855             printf("Max latency so far: %lld microseconds.\n", max_latency);
1856         }
1857 
1858         double avg_us = (double)run_time/runs;
1859         double avg_ns = avg_us * 10e3;
1860         if (force_cancel_loop || end > test_end) {
1861             printf("\n%lld total runs "
1862                 "(avg latency: "
1863                 "%.4f microseconds / %.2f nanoseconds per run).\n",
1864                 runs, avg_us, avg_ns);
1865             printf("Worst run took %.0fx longer than the average latency.\n",
1866                 max_latency / avg_us);
1867             exit(0);
1868         }
1869     }
1870 }
1871 
1872 /*------------------------------------------------------------------------------
1873  * Program main()
1874  *--------------------------------------------------------------------------- */
1875 
1876 int main(int argc, char **argv) {
1877     int firstarg;
1878 
1879     config.hostip = sdsnew("127.0.0.1");
1880     config.hostport = 6379;
1881     config.hostsocket = NULL;
1882     config.repeat = 1;
1883     config.interval = 0;
1884     config.dbnum = 0;
1885     config.interactive = 0;
1886     config.shutdown = 0;
1887     config.monitor_mode = 0;
1888     config.pubsub_mode = 0;
1889     config.latency_mode = 0;
1890     config.latency_history = 0;
1891     config.cluster_mode = 0;
1892     config.slave_mode = 0;
1893     config.getrdb_mode = 0;
1894     config.stat_mode = 0;
1895     config.scan_mode = 0;
1896     config.intrinsic_latency_mode = 0;
1897     config.pattern = NULL;
1898     config.rdb_filename = NULL;
1899     config.pipe_mode = 0;
1900     config.pipe_timeout = REDIS_CLI_DEFAULT_PIPE_TIMEOUT;
1901     config.bigkeys = 0;
1902     config.stdinarg = 0;
1903     config.auth = NULL;
1904     config.eval = NULL;
1905     config.last_cmd_type = -1;
1906 
1907     if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL))
1908         config.output = OUTPUT_RAW;
1909     else
1910         config.output = OUTPUT_STANDARD;
1911     config.mb_delim = sdsnew("\n");
1912     cliInitHelp();
1913 
1914     firstarg = parseOptions(argc,argv);
1915     argc -= firstarg;
1916     argv += firstarg;
1917 
1918     signal(SIGPIPE, SIG_IGN);
1919 
1920     /* Latency mode */
1921     if (config.latency_mode) {
1922         if (cliConnect(0) == REDIS_ERR) exit(1);
1923         latencyMode();
1924     }
1925 
1926     /* Slave mode */
1927     if (config.slave_mode) {
1928         if (cliConnect(0) == REDIS_ERR) exit(1);
1929         slaveMode();
1930     }
1931 
1932     /* Get RDB mode. */
1933     if (config.getrdb_mode) {
1934         if (cliConnect(0) == REDIS_ERR) exit(1);
1935         getRDB();
1936     }
1937 
1938     /* Pipe mode */
1939     if (config.pipe_mode) {
1940         if (cliConnect(0) == REDIS_ERR) exit(1);
1941         pipeMode();
1942     }
1943 
1944     /* Find big keys */
1945     if (config.bigkeys) {
1946         if (cliConnect(0) == REDIS_ERR) exit(1);
1947         findBigKeys();
1948     }
1949 
1950     /* Stat mode */
1951     if (config.stat_mode) {
1952         if (cliConnect(0) == REDIS_ERR) exit(1);
1953         if (config.interval == 0) config.interval = 1000000;
1954         statMode();
1955     }
1956 
1957     /* Scan mode */
1958     if (config.scan_mode) {
1959         if (cliConnect(0) == REDIS_ERR) exit(1);
1960         scanMode();
1961     }
1962 
1963     /* Intrinsic latency mode */
1964     if (config.intrinsic_latency_mode) intrinsicLatencyMode();
1965 
1966     /* Start interactive mode when no command is provided */
1967     if (argc == 0 && !config.eval) {
1968         /* Note that in repl mode we don't abort on connection error.
1969          * A new attempt will be performed for every command send. */
1970         cliConnect(0);
1971         repl();
1972     }
1973 
1974     /* Otherwise, we have some arguments to execute */
1975     if (cliConnect(0) != REDIS_OK) exit(1);
1976     if (config.eval) {
1977         return evalMode(argc,argv);
1978     } else {
1979         return noninteractive(argc,convertToSds(argc,argv));
1980     }
1981 }
1982