]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
1 /* Redis CLI (command line interface)
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
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.
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.
47 #include "linenoise.h"
49 #define REDIS_NOTUSED(V) ((void) V)
51 static struct config
{
60 int raw_output
; /* output mode per command */
61 int tty
; /* flag for default output format */
62 int stdinarg
; /* get last arg from stdin. (-x option) */
68 static int cliReadReply(int fd
);
71 /*------------------------------------------------------------------------------
73 *--------------------------------------------------------------------------- */
75 static long long mstime(void) {
79 gettimeofday(&tv
, NULL
);
80 mst
= ((long)tv
.tv_sec
)*1000;
81 mst
+= tv
.tv_usec
/1000;
85 static void printStringRepr(char *s
, int len
) {
93 case '\n': printf("\\n"); break;
94 case '\r': printf("\\r"); break;
95 case '\t': printf("\\t"); break;
96 case '\a': printf("\\a"); break;
97 case '\b': printf("\\b"); break;
102 printf("\\x%02x",(unsigned char)*s
);
110 /*------------------------------------------------------------------------------
111 * Networking / parsing
112 *--------------------------------------------------------------------------- */
114 /* Connect to the client. If force is not zero the connection is performed
115 * even if there is already a connected socket. */
116 static int cliConnect(int force
) {
117 char err
[ANET_ERR_LEN
];
118 static int fd
= ANET_ERR
;
120 if (fd
== ANET_ERR
|| force
) {
121 if (force
) close(fd
);
122 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
123 if (fd
== ANET_ERR
) {
124 fprintf(stderr
, "Could not connect to Redis at %s:%d: %s", config
.hostip
, config
.hostport
, err
);
127 anetTcpNoDelay(NULL
,fd
);
132 static sds
cliReadLine(int fd
) {
133 sds line
= sdsempty();
143 } else if ((ret
== 0) || (c
== '\n')) {
146 line
= sdscatlen(line
,&c
,1);
149 return sdstrim(line
,"\r\n");
152 static int cliReadSingleLineReply(int fd
, int quiet
) {
153 sds reply
= cliReadLine(fd
);
155 if (reply
== NULL
) return 1;
162 static int cliReadBulkReply(int fd
) {
163 sds replylen
= cliReadLine(fd
);
164 char *reply
, crlf
[2];
167 if (replylen
== NULL
) return 1;
168 bulklen
= atoi(replylen
);
174 reply
= zmalloc(bulklen
);
175 anetRead(fd
,reply
,bulklen
);
177 if (config
.raw_output
|| !config
.tty
) {
178 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
183 /* If you are producing output for the standard output we want
184 * a more interesting output with quoted characters and so forth */
185 printStringRepr(reply
,bulklen
);
191 static int cliReadMultiBulkReply(int fd
) {
192 sds replylen
= cliReadLine(fd
);
196 if (replylen
== NULL
) return 1;
197 elements
= atoi(replylen
);
198 if (elements
== -1) {
204 printf("(empty list or set)\n");
207 if (config
.tty
) printf("%d. ", c
);
208 if (cliReadReply(fd
)) retval
= 1;
209 if (elements
) printf("%c",config
.mb_sep
);
215 static int cliReadReply(int fd
) {
219 if ((nread
= anetRead(fd
,&type
,1)) <= 0) {
220 if (config
.shutdown
) return 0;
221 if (config
.interactive
&&
222 (nread
== 0 || (nread
== -1 && errno
== ECONNRESET
)))
226 printf("I/O error while reading from socket: %s",strerror(errno
));
232 if (config
.tty
) printf("(error) ");
233 cliReadSingleLineReply(fd
,0);
236 return cliReadSingleLineReply(fd
,0);
238 if (config
.tty
) printf("(integer) ");
239 return cliReadSingleLineReply(fd
,0);
241 return cliReadBulkReply(fd
);
243 return cliReadMultiBulkReply(fd
);
245 printf("protocol error, got '%c' as reply type byte", type
);
250 static int selectDb(int fd
) {
255 if (config
.dbnum
== 0)
259 cmd
= sdscatprintf(cmd
,"SELECT %d\r\n",config
.dbnum
);
260 anetWrite(fd
,cmd
,sdslen(cmd
));
261 anetRead(fd
,&type
,1);
262 if (type
<= 0 || type
!= '+') return 1;
263 retval
= cliReadSingleLineReply(fd
,1);
270 static void showInteractiveHelp(void) {
273 "Welcome to redis-cli " REDIS_VERSION
"!\n"
274 "Just type any valid Redis command to see a pretty printed output.\n"
276 "It is possible to quote strings, like in:\n"
277 " set \"my key\" \"some string \\xff\\n\"\n"
279 "You can find a list of valid Redis commands at\n"
280 " http://code.google.com/p/redis/wiki/CommandReference\n"
282 "Note: redis-cli supports line editing, use up/down arrows for history."
286 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
287 char *command
= argv
[0];
288 int fd
, j
, retval
= 0;
291 config
.raw_output
= !strcasecmp(command
,"info");
292 if (!strcasecmp(command
,"help")) {
293 showInteractiveHelp();
296 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
297 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
298 if (!strcasecmp(command
,"subscribe") ||
299 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
300 if ((fd
= cliConnect(0)) == -1) return 1;
302 /* Select db number */
303 retval
= selectDb(fd
);
305 fprintf(stderr
,"Error setting DB num\n");
309 /* Build the command to send */
310 cmd
= sdscatprintf(sdsempty(),"*%d\r\n",argc
);
311 for (j
= 0; j
< argc
; j
++) {
312 cmd
= sdscatprintf(cmd
,"$%lu\r\n",
313 (unsigned long)sdslen(argv
[j
]));
314 cmd
= sdscatlen(cmd
,argv
[j
],sdslen(argv
[j
]));
315 cmd
= sdscatlen(cmd
,"\r\n",2);
319 anetWrite(fd
,cmd
,sdslen(cmd
));
320 while (config
.monitor_mode
) {
321 if (cliReadSingleLineReply(fd
,0)) exit(1);
325 if (config
.pubsub_mode
) {
326 printf("Reading messages... (press Ctrl-c to quit)\n");
333 retval
= cliReadReply(fd
);
334 if (!config
.raw_output
&& config
.tty
) printf("\n");
335 if (retval
) return retval
;
340 /*------------------------------------------------------------------------------
342 *--------------------------------------------------------------------------- */
344 static int parseOptions(int argc
, char **argv
) {
347 for (i
= 1; i
< argc
; i
++) {
348 int lastarg
= i
==argc
-1;
350 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
351 char *ip
= zmalloc(32);
352 if (anetResolve(NULL
,argv
[i
+1],ip
) == ANET_ERR
) {
353 printf("Can't resolve %s\n", argv
[i
]);
358 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
360 } else if (!strcmp(argv
[i
],"-x")) {
362 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
363 config
.hostport
= atoi(argv
[i
+1]);
365 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
366 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
368 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
369 config
.dbnum
= atoi(argv
[i
+1]);
371 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
372 config
.auth
= argv
[i
+1];
374 } else if (!strcmp(argv
[i
],"-i")) {
376 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
377 "by default when redis-cli is executed without a command to execute.\n"
379 } else if (!strcmp(argv
[i
],"-c")) {
381 "Reading last argument from standard input using -c is deprecated.\n"
382 "When standard input is connected to a pipe or regular file, it is\n"
383 "automatically used as last argument.\n"
385 } else if (!strcmp(argv
[i
],"-v")) {
386 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION
);
395 static sds
readArgFromStdin(void) {
397 sds arg
= sdsempty();
400 int nread
= read(fileno(stdin
),buf
,1024);
402 if (nread
== 0) break;
403 else if (nread
== -1) {
404 perror("Reading from standard input");
407 arg
= sdscatlen(arg
,buf
,nread
);
412 static void usage() {
413 fprintf(stderr
, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
414 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
415 fprintf(stderr
, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
416 fprintf(stderr
, "example: redis-cli get my_passwd\n");
417 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
418 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
422 /* Turn the plain C strings into Sds strings */
423 static char **convertToSds(int count
, char** args
) {
425 char **sds
= zmalloc(sizeof(char*)*count
);
427 for(j
= 0; j
< count
; j
++)
428 sds
[j
] = sdsnew(args
[j
]);
433 #define LINE_BUFLEN 4096
439 config
.interactive
= 1;
440 while((line
= linenoise("redis> ")) != NULL
) {
441 if (line
[0] != '\0') {
442 argv
= sdssplitargs(line
,&argc
);
443 linenoiseHistoryAdd(line
);
444 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
446 printf("Invalid argument(s)\n");
448 } else if (argc
> 0) {
449 if (strcasecmp(argv
[0],"quit") == 0 ||
450 strcasecmp(argv
[0],"exit") == 0)
455 long long start_time
= mstime(), elapsed
;
457 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
458 if (err
== ECONNRESET
) {
459 printf("Reconnecting... ");
461 if (cliConnect(1) == -1) exit(1);
463 cliSendCommand(argc
,argv
,1);
466 elapsed
= mstime()-start_time
;
467 if (elapsed
> 500) printf("%.2f seconds\n",
468 (double)elapsed
/1000);
471 /* Free the argument vector */
472 for (j
= 0; j
< argc
; j
++)
476 /* linenoise() returns malloc-ed lines like readline() */
482 static int noninteractive(int argc
, char **argv
) {
484 if (config
.stdinarg
) {
485 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
486 argv
[argc
] = readArgFromStdin();
487 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
489 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
490 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
495 int main(int argc
, char **argv
) {
498 config
.hostip
= "127.0.0.1";
499 config
.hostport
= 6379;
502 config
.interactive
= 0;
504 config
.monitor_mode
= 0;
505 config
.pubsub_mode
= 0;
506 config
.raw_output
= 0;
509 config
.historyfile
= NULL
;
510 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
511 config
.mb_sep
= '\n';
513 if (getenv("HOME") != NULL
) {
514 config
.historyfile
= malloc(256);
515 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
516 linenoiseHistoryLoad(config
.historyfile
);
519 firstarg
= parseOptions(argc
,argv
);
523 if (config
.auth
!= NULL
) {
525 int dbnum
= config
.dbnum
;
527 /* We need to save the real configured database number and set it to
528 * zero here, otherwise cliSendCommand() will try to perform the
529 * SELECT command before the authentication, and it will fail. */
531 authargv
[0] = "AUTH";
532 authargv
[1] = config
.auth
;
533 cliSendCommand(2, convertToSds(2, authargv
), 1);
534 config
.dbnum
= dbnum
; /* restore the right DB number */
537 /* Start interactive mode when no command is provided */
538 if (argc
== 0) repl();
539 /* Otherwise, we have some arguments to execute */
540 return noninteractive(argc
,convertToSds(argc
,argv
));